{"owner":"google-gemini","repo":"cookbook","hasSkills":true,"totalSkillsCount":6,"totalTokensCount":7926,"categories":["plugin-manifest","anthropic-skill","project-spec"],"hasMcp":false,"mcpConfig":null,"found":["tools/README.md","tools/link_checker/Design.md","tools/Design.md","tools/nb_tester/README.md","tools/nb_tester/rules/default_rules.yaml","tools/nb_tester/Design.md"],"skills":{"tools/README.md":"# Gemini API Cookbook Quality Assurance & Linting Tools\n\nThis directory contains standalone tools for formatting, linting, and maintaining Jupyter/Colab notebooks in the [Gemini API Cookbook](https://github.com/google-gemini/cookbook).\n\nThese tools are natively hosted in this repository to provide fast, zero-dependency validation tailored specifically to the Gemini SDK and cookbook style guidelines.\n\n---\n\n## Tools Overview\n\n| Tool | Script | Description |\n| :--- | :--- | :--- |\n| **`nblint`** | `tools/nblint_cli.py` | Lints notebooks for licensing, structure, style, SDK best practices, and model selectors. |\n| **`nbfmt`** | `tools/nbfmt_cli.py` | Automatically formats notebook JSON, standardizes metadata, strips empty cells, and aligns code formatting. |\n| **`readme_links`** | `tools/check_readme_links.py` | Validates that new/modified notebooks are linked in section Table of Contents READMEs. |\n| **`check_all_links`** | `tools/check_all_links.py` | Audits internal paths, anchors, blob URLs, and external links across `.md` and `.ipynb` files. |\n| **`config`** | `tools/config.py` | Central configuration file containing model hierarchies, wordlists, exclusions, and URL rules. |\n\n---\n\n## 1. Quickstart Usage\n\n### Linting Notebooks\n```bash\n# Lint a specific notebook\npython tools/nblint_cli.py quickstarts/Get_started.ipynb\n\n# Lint multiple notebooks or directories\npython tools/nblint_cli.py quickstarts/**/*.ipynb examples/**/*.ipynb\n\n# Perform a dry-run check\npython tools/nblint_cli.py --dry-run quickstarts/Get_started.ipynb\n\n# Specify custom branch or repository\npython tools/nblint_cli.py --repo=google-gemini/cookbook --branch=main path/to/notebook.ipynb\n```\n\n### Formatting Notebooks\n```bash\n# Format a specific notebook (modifies file in place)\npython tools/nbfmt_cli.py quickstarts/Get_started.ipynb\n\n# Test if notebooks are properly formatted (without modifying, returns non-zero on unformatted)\npython tools/nbfmt_cli.py --test quickstarts/**/*.ipynb\n\n# Format all notebooks in the repo\npython tools/nbfmt_cli.py quickstarts/**/*.ipynb examples/**/*.ipynb\n```\n\n### Checking Table of Contents README Links\n```bash\n# Check if a specific notebook is linked in its folder/section README.md\npython tools/check_readme_links.py quickstarts/Get_started.ipynb\n\n# Audit all notebooks in the repo\npython tools/check_readme_links.py --all\n```\n\n### Verifying Internal and External Links\n```bash\n# Validate internal links and anchors on specific files (fast CI check)\npython tools/check_all_links.py quickstarts/Get_started.ipynb README.md\n\n# Validate all git-modified files against upstream/main\npython tools/check_all_links.py --changed\n\n# Full repository audit of all internal relative links and anchor slugs\npython tools/check_all_links.py\n\n# Full repository audit including live external HTTP/HTTPS health checks\npython tools/check_all_links.py --all\n```\n\n---\n\n## 2. Lint Rules Reference\n\n### Python Syntax Rules (`tools/nblint/rules/syntax.py`)\n- **`syntax::code_cell`**: Parses code cells, including `%%time` bodies, with `ast.parse` after neutralizing IPython magics and shell escapes. Other `%%` cell magics are skipped. Reports the cell index and original line of any `SyntaxError`.\n\n### Structure Rules (`tools/nblint/rules/structure.py`)\n- **`structure::copyright`**: Verifies that cell 0 contains a valid Google / Gemini copyright statement (`##### Copyright 2026 Google LLC.`).\n- **`structure::license`**: Verifies that the notebook contains a collapsed Apache 2.0 license code cell with `# @title Licensed under the Apache License`.\n- **`structure::colab_button`**: Checks for the \"Open in Colab\" badge and verifies that its destination URL matches `https://colab.research.google.com/github/<repo>/blob/<branch>/<path>`. Automatically adjusts for redirect stubs.\n- **`structure::next_steps`**: Emits a warning if a closing section is missing. Accepted headings: \"Next steps\", \"What's next\", \"Learn more\" / \"Learning more\", \"Further reading\" / \"Further resources\" or \"Conclusion\".\n\n### Style & Language Rules (`tools/nblint/rules/style.py`)\n- **`style::inclusive_language`**: Flags discouraged terminology (`blacklist`, `whitelist`, `master`, `slave`) and suggests modern alternatives. **Note**: The word `\"native\"` is deliberately allowed because terms like *\"native audio\"*, *\"native TTS\"*, and *\"native multimodal\"* are standard Gemini API features.\n- **`style::second_person`**: Ensures narrative explanations in markdown use second person (*you*) rather than first person (*we*). Prompt strings, quoted examples, and code comments are ignored.\n- **`style::line_length`**: Warns when code lines exceed 100 characters (ignoring URLs, form annotations, and long multiline strings).\n\n### Gemini SDK & API Best Practices (`tools/nblint/rules/gemini.py`)\n- **`gemini::pip_magic`**: Enforces `%pip install` instead of `!pip install` for reliable kernel-level package installation.\n- **`gemini::sdk_package`**: Enforces the official `from google import genai` (`google-genai`) SDK, flagging deprecated `google.generativeai`.\n- **`gemini::api_key_secret`**: Checks that notebooks retrieve API keys from `userdata.get('GEMINI_API_KEY')` rather than the legacy `GOOGLE_API_KEY` secret.\n- **`gemini::hardcoded_api_key`**: Scans all cells for accidental plaintext Google/Gemini API keys (legacy `AIza...` and new `AQ.Ab8...` formats) to prevent credential leakage.\n\n### Model Selector Validation (`tools/nblint/rules/model_selector.py`)\n- **`gemini::model_selector`**:\n  - Verifies that model selectors use the canonical Colab form pattern:\n    ```python\n    MODEL_ID = \"gemini-3.7-flash\" # @param [\"gemini-3.1-pro-preview\", \"gemini-3.7-flash\", \"gemini-3.5-flash-lite\"] {\"allow-input\":true, isTemplate: true}\n    ```\n  - Verifies that the default assigned model exists in the option list.\n  - Verifies that models in the list are sorted in logical order from most capable to least capable: **current generation (Pro $\\rightarrow$ Flash $\\rightarrow$ Flash-Lite)**, followed by **previous generation (e.g. Gemini 3.x)**.\n\n---\n\n## 3. Configuration & Exclusions\n\nAll configurable settings are consolidated in `tools/config.py`:\n- **`EXCLUDED_NOTEBOOKS`**: List of files skipped during automated lint runs (e.g. `quickstarts/Template.ipynb`).\n- **`REDIRECT_KEYWORDS`**: Keywords used to automatically detect redirection stubs (e.g. `gemini-robotics-er.ipynb`) and apply lenient rules.\n- **`get_model_sort_key(model_name)`**: Ranking algorithm for model selector ordering.\n- **`INCLUSIVE_LANGUAGE_WORDLIST`**: Mapping of discouraged terms to replacements.\n","tools/link_checker/Design.md":"# Architecture & Design: Cookbook Link Checker (`tools/check_all_links.py`)\n\n## 1. Overview & Objectives\n\nThe **Cookbook Link Checker** is an automated quality gate designed to prevent broken, dead, or misdirected links from entering the `google-gemini/cookbook` repository. It audits both Markdown documentation (`.md`) and Jupyter Notebooks (`.ipynb`), providing sub-second validation for Pull Requests and comprehensive health checks for scheduled maintenance.\n\n### Primary Goals:\n1. **Zero Broken Links at PR Merge**: Catch renamed notebooks, deleted files, invalid relative paths, and broken anchor links before merging.\n2. **Sub-Second CI Runtime**: Ensure that PR checks on modified files execute in `<1-2s` without depending on external network calls.\n3. **Deep Anchor Validation**: Validate `#anchor-name` targets both in-page and cross-file, matching GitHub's Markdown slugification rules and HTML `<a name=\"...\">` tags.\n4. **Seamless Integration**: Native Python standard library implementation with zero external dependencies (no `requests`, `beautifulsoup4`, or `curl` required).\n\n---\n\n## 2. Architecture & Scanning Pipeline\n\n```mermaid\nflowchart TD\n    A[\"CLI / CI Trigger\"] --> B[\"Target File Resolution<br/>(explicit paths, --changed, or full repo)\"]\n    B --> C[\"Link Extraction<br/>(Markdown [text](url) & HTML <a href=...>)\"]\n    C --> D{\"Scheme & Pattern Filter\"}\n    D -->|\"data:, mailto:, tel:, javascript:\"| E[\"Ignored / Skipped\"]\n    D -->|\"Blob URL: github.com/.../blob/main/...\"| F[\"Local Disk Path Resolver\"]\n    D -->|\"Internal Relative Path<br/>(../path.ipynb#heading)\"| G[\"Path Traversal & Anchor Checker\"]\n    D -->|\"External HTTP/HTTPS<br/>(when --all enabled)\"| H[\"Concurrent Worker Pool<br/>(ThreadPoolExecutor)\"]\n    \n    F --> I[\"Anchor & File Validator\"]\n    G --> I\n    I --> J[\"In-Memory Anchor Cache<br/>(_anchors_cache)\"]\n    \n    H --> K{\"HEAD Status\"}\n    K -->|\"200-399\"| L[\"Valid\"]\n    K -->|\"403 / 405\"| M[\"Fallback to GET\"]\n    K -->|\"404 / 500 / Timeout\"| N[\"Report Broken\"]\n    \n    I --> O[\"Aggregation & Exit Code\"]\n    N --> O\n    L --> O\n```\n\n---\n\n## 3. Link Categories & Resolution Rules\n\n### 3.1 Internal Relative Links (`./...`, `../...`)\n- Resolves paths relative to the parent directory of the source file.\n- Guards against path traversal vulnerabilities by enforcing `target_path.relative_to(repo_root)`.\n- Verifies physical file existence on disk.\n\n### 3.2 GitHub Repository Blob URLs (`https://github.com/google-gemini/cookbook/blob/main/...`)\n- Contributors often write absolute GitHub blob URLs pointing to other cookbook files.\n- The tool intercepts links starting with `https://github.com/google-gemini/cookbook/blob/main/` and maps them directly to the local clone working tree.\n- Catches broken links introduced during renames even if the external branch has not yet been pushed or merged.\n\n### 3.3 Anchor Fragment Verification (`#...`)\n- **Colab UI Fragments**: `#scrollTo=...` is recognized as a Google Colab cell identifier and validated against cell IDs or gracefully allowed.\n- **In-Page Anchors**: `#heading-title` in `README.md` validates that `heading-title` exists as a slugified heading or HTML `<a name=\"...\">` in `README.md`.\n- **Cross-File Anchors**: `quickstarts/Get_started.ipynb#audio` validates that `quickstarts/Get_started.ipynb` exists and contains an anchor or heading slug matching `audio`.\n- **Anchor Caching**: Targets are parsed once and cached in `_anchors_cache` to keep multi-thousand link audits under 2 seconds.\n\n### 3.4 Data URIs & Media Exclusions\n- Inline image data (`![img](data:image/png;base64,...)`) is excluded via `re.compile(r\"^data:\")` to prevent massive base64 string dumps in error logs.\n- Documentation template placeholders (`URL`, `TODO`) are whitelisted via `LINK_CHECKER_EXCLUDED_TARGETS` in `tools/config.py`.\n\n### 3.5 External HTTP/HTTPS Links (`--all`)\n- Uses `concurrent.futures.ThreadPoolExecutor(max_workers=16)` for parallel HTTP verification.\n- Dispatches HTTP `HEAD` with standard browser `User-Agent`.\n- Automatically retries with HTTP `GET` if the target server rejects `HEAD` with `405 Method Not Allowed` or `403 Forbidden`.\n- Bypasses ignored domains (`localhost`, `127.0.0.1`, Google API endpoints requiring API keys).\n\n---\n\n## 4. GitHub Actions CI Integration\n\nThe workflow `.github/workflows/link_checker.yml` operates in three modes:\n\n1. **Pull Request Mode (`pull_request`)**:\n   - Computes changed files via `git merge-base HEAD ${{ github.event.pull_request.base.sha }}`.\n   - Audits only modified `.ipynb` and `.md` files in `--internal-only` mode.\n   - Completes in `<2` seconds, blocking regressions with zero flaky external network failures.\n2. **Weekly Scheduled Health Check (`schedule: cron '0 8 * * 1'`)**:\n   - Runs on Mondays at 08:00 UTC.\n   - Audits all internal paths AND performs concurrent external HTTP validation across all URLs.\n3. **Manual Dispatch (`workflow_dispatch`)**:\n   - Enables maintainers to run full audits on demand with an optional `check_external` boolean flag.\n","tools/Design.md":"# Gemini API Cookbook Quality Assurance Tools: Architecture & Design\n\n## 1. Background & Motivation\n\nPreviously, the Gemini API Cookbook's CI and developer workflows relied on the external package `tensorflow-docs` (`github.com/tensorflow/docs`) for notebook formatting (`nbfmt`) and linting (`nblint`).\n\nThis legacy setup created several critical operational problems:\n1. **External Dependency**: CI had to install `git+https://github.com/tensorflow/docs` on every workflow run. Any changes or fixes required modifying a separate repository.\n2. **False Positives on \"native\"**: `tensorflow/docs` included `\"native\": \"built-in\"` in its inclusive language wordlist. In the Gemini ecosystem, terms like *\"native audio\"*, *\"native TTS\"*, *\"native multimodal output\"*, and model IDs like `gemini-2.5-flash-native-audio-preview` are official terminology, causing CI to fail on valid PRs.\n3. **Overly Strict First-Person Flags**: The legacy linter flagged words like `\"we\"` inside code comments and string parameters (e.g. `text_prompt = \"we can see the stage...\"`).\n4. **Irrelevant Legacy Rules**: Checks for TensorFlow 1.x `r1/` directories and `tfhub.dev` buttons had to be manually excluded in CI commands.\n5. **Lack of Gemini-Specific Checks**: Common review issues—such as using `!pip` instead of `%pip`, legacy `google.generativeai` imports, `GOOGLE_API_KEY` vs `GEMINI_API_KEY`, model selector ordering, and hardcoded API keys—had to be caught manually by maintainers.\n\n## 2. Design Principles & Goals\n\n1. **Zero External Tool Dependencies**: Implemented using standard Python libraries (`json`, `pathlib`, `re`, `logging`, `argparse`, `dataclasses`).\n2. **Centralized Configuration**: All configurable parameters, model order ranks, excluded files, and wordlists reside in `tools/config.py`.\n3. **Modular Rule Architecture**: Separate rule modules for structure, style, SDK best practices, and model selector formatting.\n4. **First-Class Support for Special Notebooks**:\n   - **Template Notebook**: Explicitly excluded from full strictness tests.\n   - **Redirect Stubs**: Auto-detected via cell count and content keywords, skipping full content and Colab button mismatch failures.\n5. **Comprehensive Logging & Dry-Run**: Detailed INFO and DEBUG logs, and full `--dry-run` and `--test` support for safe local and CI testing.\n\n## 3. Directory Layout\n\n```\ntools/\n├── __init__.py\n├── config.py                 # Centralized configuration & model hierarchies\n├── nblint/                   # Linter core & rule implementations\n│   ├── __init__.py\n│   ├── linter.py             # Linter execution engine & result aggregation\n│   └── rules/\n│       ├── __init__.py\n│       ├── structure.py      # Copyright, License, Colab button, Next steps\n│       ├── style.py          # Inclusive language (no native), Second person\n│       ├── gemini.py         # %pip vs !pip, google-genai SDK, GEMINI_API_KEY, no leaks\n│       └── model_selector.py # @param Colab form & model ordering validation\n├── nbfmt/                    # Formatter core\n│   ├── __init__.py\n│   └── formatter.py          # JSON normalization, metadata & cell cleaning\n├── nblint_cli.py             # CLI entrypoint for linting\n├── nbfmt_cli.py             # CLI entrypoint for formatting\n├── README.md                 # User guide and CLI reference\n└── Design.md                 # Architecture and design rationale (this document)\n```\n\n## 4. Model Hierarchy & Ordering Logic\n\nIn `tools/config.py`, the model selector rule sorts models using `get_model_sort_key()`:\n- **Capability Tiers**: Models are ordered from most capable to least capable: Pro $\\rightarrow$ Flash $\\rightarrow$ Flash-Lite $\\rightarrow$ Domain-specific (Live/Veo/Imagen/Lyria).\n- **Generations**: Current generation models (e.g. Gemini 4.x) precede previous generations (e.g. Gemini 3.x).\n","tools/nb_tester/README.md":"# 🧪 Gemini API Cookbook Notebook Testing & Regression Suite\n\nAn automated, security-gated test runner and semantic regression evaluator designed specifically for the Jupyter/Colab notebooks in the [Gemini API Cookbook](https://github.com/google-gemini/cookbook).\n\n---\n\n## 🌟 Key Features\n\n1. **🔒 Multi-Layer Security Architecture (Preventing RCE & Key Theft)**:\n   - **Level 1 (Static AST Scanner)**: Fast, zero-secret AST checks for forbidden system calls, reverse shells, and raw environment dumps.\n   - **Level 2 (Gemini AI Security Auditor)**: Semantic code review with structured JSON output before any code execution to detect subtle backdoors, malicious `%pip` dependencies, or data exfiltration.\n   - **Zero-Disk-Tampering Colab Mock**: Injects a virtual `google.colab.userdata` module into the kernel namespace in memory, keeping notebooks clean and keys secure.\n2. **⚖️ Semantic Output Regression Judging**:\n   - Compares newly generated outputs with the saved reference outputs in the repository.\n   - Uses Gemini AI Judge to separate normal non-deterministic phrasing differences (`SLIGHT_VARIATION`) from true broken answers or hallucinations (`REGRESSION`).\n3. **🌐 Google Search Grounding Verification**:\n   - For real-time and time-evolving queries (e.g. sports scores, weather, current events), uses Gemini with the Google Search tool to double-check that new answers are factually true today.\n4. **📋 Declarative Rules & Exception Registry (`rules/default_rules.yaml`)**:\n   - Easily configure cell-level actions (e.g. skipping interactive `input()` cells) and per-notebook timeouts.\n5. **🎯 Family-Aware Dynamic Model Identifier Override (`--model <name>`)**:\n   - Test the entire cookbook (or specific notebooks) against candidate or pre-release models (e.g. `gemini-4-hydrogen`, `gemini-3.8-flash`, `gemini-3.1-pro-preview`) by dynamically overriding `MODEL_ID` in memory across compatible cells without touching disk.\n   - Automatically preserves specialized non-text models (`-live`, `-tts`, `-image`, `embedding`, `veo`, `lyria`, `transcribe`) unless the override model itself belongs to that same model family.\n6. **📊 CI & Pull Request Integration**:\n   - Generates persistent JSON reports under `reports/` and auto-appends formatted Markdown tables to `$GITHUB_STEP_SUMMARY`.\n   - Returns clean exit codes (`0` on pass, `1` on failure) for automated gating.\n7. **🔍 Dry-Run Mode**:\n   - Test rule configurations, AST checks, model overrides, and syntax parsing without altering files, spinning up kernels, or consuming API tokens.\n8. **🔁 Automatic Cell-Level Retry & Exponential Backoff**:\n   - Automatically retries failed cells (up to 3 times by default with exponential backoff) on transient API errors (429, 503, timeouts) before failing, preventing flaky CI runs while skipping non-retryable syntax errors. Configurable via `--max-retries` CLI flag or `rules/default_rules.yaml`.\n\n---\n\n## 🛠️ System Prerequisites (Local Execution)\n\nIn Google Colab, `ffmpeg`, `jq`, and `curl` are pre-installed in the default runtime container (and `poppler-utils` is installed via `!apt-get install -y -q poppler-utils` inside `quickstarts/PDF_Files.ipynb`).\n\nWhen running `tools/nb_tester` locally on a Linux/macOS workstation or headless CI runner (where notebooks do not execute as `root`), install the following system packages first so audio, video, PDF (`pdf2image` / `pdftoppm`), and REST (`curl` + `jq`) notebooks execute cleanly:\n\n```bash\n# Ubuntu / Debian / gLinux\nsudo apt-get update && sudo apt-get install -y ffmpeg poppler-utils jq curl\n```\n\n---\n\n## 🚀 Quickstart & Usage\n\n### 1. Dry-Run Mode (Safe simulation)\n```bash\npython3 -m tools.nb_tester.cli --notebook quickstarts/Counting_Tokens.ipynb --dry-run\n```\n\n### 2. Security Audit Only (No code execution)\n```bash\npython3 -m tools.nb_tester.cli --notebook quickstarts/Prompting.ipynb --security-only\n```\n\n### 3. Test a Single Notebook with Live Execution & AI Judge\n```bash\nexport GEMINI_API_KEY=\"your-api-key\"\npython3 -m tools.nb_tester.cli --notebook quickstarts/Counting_Tokens.ipynb\n```\n\n### 4. Test Only Changed Notebooks in a PR / Git Branch\n```bash\npython3 -m tools.nb_tester.cli --changed\n```\n\n### 5. Test Notebooks with Dynamic Model Override\n```bash\n# Run a specific quickstart against a candidate/preview model\npython3 -m tools.nb_tester.cli --notebook quickstarts/Get_started_thinking.ipynb --model gemini-3.1-pro-preview\n\n# Run all quickstarts with model override in parallel\npython3 -m tools.nb_tester.cli --all --model gemini-3.7-flash --workers 4\n```\n\n### 6. Run Full Suite in Parallel\n```bash\npython3 -m tools.nb_tester.cli --all --workers 4\n```\n\n---\n\n## ⚙️ Configuration & Exception Rules\n\nRules are declared in `tools/nb_tester/rules/default_rules.yaml`.\n\n```yaml\nglobal_defaults:\n  cell_timeout_sec: 90\n  notebook_timeout_sec: 600\n  default_strategy: \"semantic_llm\"\n\nnotebooks:\n  quickstarts/Grounding.ipynb:\n    cells:\n      - match: \"client.models.generate_content\"\n        strategy: \"grounded_factual\"\n        description: \"Verify dynamic search output using Google Search\"\n\n  quickstarts/Interactive_Chat.ipynb:\n    cells:\n      - match: \"input(\"\n        action: \"skip\"\n        reason: \"Interactive user input not supported in headless CI\"\n```\n\n---\n\n## 🏗️ Architecture & Modules\n\n```\ntools/nb_tester/\n├── config.py             # Centralized models, timeouts, and GEMINI_API_KEY resolution\n├── logger.py             # Structured logging with complete LLM prompt/response tracking\n├── security_scanner.py   # Level 1: Deterministic AST & regex scanner\n├── ai_security_auditor.py# Level 2: Gemini AI Semantic Security Auditor\n├── rules.py              # Declarative rules engine and matcher\n├── model_override.py     # In-memory MODEL_ID override transformer & preamble injector\n├── executor.py           # nbclient kernel executor with in-memory Colab mock\n├── comparator.py         # Output snapshot extractor and strategy router\n├── llm_judge.py          # Level 3: Semantic output regression judge\n├── grounded_verifier.py  # Real-time fact-checking via Google Search Grounding\n├── reporter.py           # Multi-format report builder (JSON, Step Summary, Terminal)\n├── cli.py                # Command-line interface entry point\n└── rules/\n    └── default_rules.yaml# Default rule definitions and exceptions\n```\n","tools/nb_tester/rules/default_rules.yaml":"# Copyright 2026 Google LLC\n# Default Testing & Exception Rules for Gemini API Cookbook Notebooks\n\n# Global defaults across all notebooks unless overridden\nglobal_defaults:\n  cell_timeout_sec: 240\n  notebook_timeout_sec: 1200\n  default_strategy: \"semantic_llm\"\n  cell_max_retries: 3\n  cell_retry_backoff_sec: 2.0\n\n# Specific notebook overrides\nnotebooks:\n  quickstarts/Counting_Tokens.ipynb:\n    cell_timeout_sec: 60\n    cells:\n      - match: \"client.models.count_tokens\"\n        strategy: \"exact_or_fuzzy\"\n        description: \"Token counting outputs are deterministic integers\"\n\n  quickstarts/Grounding.ipynb:\n    cells:\n      - match: \"client.models.generate_content\"\n        strategy: \"grounded_factual\"\n        description: \"Live search grounded responses may evolve over time; double check with Google Search\"\n\n  quickstarts/Search_Grounding.ipynb:\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1200\n    allow_dynamic_exec: true\n    allow_security_demo: true\n    cells:\n      - match: \"client.models.generate_content\"\n        strategy: \"grounded_factual\"\n        description: \"Verify factual correctness of live Google Search results\"\n\n  quickstarts/JSON_mode.ipynb:\n    cells:\n      - match: \"response_mime_type=\\\"application/json\\\"\"\n        strategy: \"schema_validation\"\n        description: \"Validates JSON structure conformance\"\n\n  quickstarts/Interactive_Chat.ipynb:\n    cells:\n      - match: \"input(\"\n        action: \"skip\"\n        reason: \"Interactive user input cell cannot execute in headless CI\"\n\n  quickstarts/Authentication_with_OAuth.ipynb:\n    skip_notebook: true\n    skip_reason: \"Requires interactive browser OAuth login flow\"\n\n  quickstarts/Webhooks.ipynb:\n    skip_notebook: true\n    skip_reason: \"Requires live webhook receiver server endpoint\"\n\n  quickstarts/Get_started_Veo.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1500\n    description: \"Video generation takes longer than text generation\"\n\n  quickstarts/Get_started_Veo_REST.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1500\n    description: \"REST Veo video generation and polling\"\n\n  quickstarts/Batch_mode.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1800\n    description: \"Asynchronous Batch API job polling can take 5-15 minutes\"\n\n  quickstarts/File_API.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1500\n    description: \"Uploads and processes a 45-minute video via File API\"\n\n  quickstarts/Get_started_Lyria.ipynb:\n    long_running: true\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1200\n    description: \"Real-time Lyria music generation streaming\"\n\n  quickstarts/Tuning.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1800\n    description: \"Model tuning job creation and training loop\"\n\n  quickstarts/Get_started_Deep_Research.ipynb:\n    long_running: true\n    cell_timeout_sec: 1800\n    notebook_timeout_sec: 2400\n    description: \"Deep Research queries can take up to 30+ minutes\"\n\n  quickstarts/Get_Started_Nano_Banana.ipynb:\n    cell_timeout_sec: 180\n    notebook_timeout_sec: 1800\n    description: \"Image generation and multi-turn image editing\"\n\n  quickstarts/Get_started_thinking.ipynb:\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1800\n    description: \"Extended thinking generation chains can take up to 10 minutes per cell\"\n\n  quickstarts/Get_started_thinking_REST.ipynb:\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1200\n    description: \"Thinking REST endpoint multi-turn analysis\"\n\n  quickstarts/Get_started_Omni.ipynb:\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1200\n    description: \"Omni multimodal model processing\"\n\n  quickstarts/Video_understanding.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1500\n    description: \"Video upload, processing, and multi-turn frame analysis\"\n\n  quickstarts/Inference_tiers.ipynb:\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1200\n    description: \"Multi-tier model benchmarking and latency comparison\"\n\n  quickstarts/Get_started.ipynb:\n    cell_timeout_sec: 300\n    notebook_timeout_sec: 1200\n    description: \"Full tour of multimodal features across large files\"\n\n  examples/Virtual_Try_On.ipynb:\n    skip_notebook: true\n    skip_reason: \"Requires interactive Colab Vertex AI auth (auth.authenticate_user)\"\n\n  examples/Google_IO2025_Live_Coding.ipynb:\n    skip_notebook: true\n    skip_reason: \"Historical event notebook kept frozen with original Google I/O 2025 models\"\n\n  examples/Book_illustration.ipynb:\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1800\n    description: \"Multimodal audio, TTS, image generation, and MoviePy mix\"\n\n  examples/gemini_google_adk_model_guardrails.ipynb:\n    allow_security_demo: true\n    description: \"Demonstrates model guardrails against prompt injection and backdoors\"\n\n  examples/LiveAPI_plotting_and_mapping.ipynb:\n    allow_dynamic_exec: true\n    allow_security_demo: true\n    description: \"Demonstrates live plotting and mapping using code execution tools\"\n\n  examples/prompting/Basic_Code_Generation.ipynb:\n    allow_dynamic_exec: true\n    allow_security_demo: true\n    description: \"Demonstrates generating and executing Python code via exec()\"\n","tools/nb_tester/Design.md":"# 📐 Design Document: Notebook Automated Testing, Security & Regression Suite\n\n## 1. Context & Objectives\n\nThe **Gemini API Cookbook** is a central public repository of Python/Jupyter tutorials. Maintaining quality across rapid model releases and SDK iterations introduces two fundamental challenges:\n1. **Security in Open-Source PRs**: Untrusted pull requests from public contributors could execute arbitrary code (RCE) or exfiltrate repo secrets/tokens (`GEMINI_API_KEY`).\n2. **Non-Deterministic Semantic Regressions**: Code might run without raising an exception (exit code 0), but the model's output could regress into low-quality answers, hallucinations, or broken formats.\n3. **Dynamic & Evolving Data**: Grounded search queries (e.g. sports scores, weather) will naturally change over time and require factual verification rather than static string matching.\n\n---\n\n## 2. Threat Model & Multi-Layer Safety Defense\n\n```mermaid\nflowchart TD\n    subgraph Gate1 [Gate 1: Static AST &amp; Regex Scanner]\n        A[PR / Target Notebook] --> B[Parse Code Cells to AST]\n        B --> C{Forbidden calls? eval, exec, os.environ dump}\n        C -- Yes --> D[🚨 Hard Block - Critical Finding]\n        C -- No --> Gate2\n    end\n\n    subgraph Gate2 [Gate 2: Semantic AI Security Auditor]\n        Gate2[Gemini AI Security Model] --> E[Analyze code logic &amp; external URLs]\n        E --> F{Risk Score &lt;= 3 and Verdict == SAFE?}\n        F -- No --> G[🚨 Security Block - Human Review Required]\n        F -- Yes --> Gate3\n    end\n\n    subgraph Gate3 [Gate 3: Isolated Execution &amp; Colab Mock]\n        Gate3[Ephemeral Kernel] --> H[Inject in-memory google.colab.userdata]\n        H --> I[Execute cell-by-cell with timeouts]\n        I --> J[Capture Outputs &amp; Tracebacks]\n    end\n\n    subgraph Gate4 [Gate 4: Output Evaluation &amp; Fact-Checking]\n        J --> K[Exact / Fuzzy / Schema Check]\n        J --> L[Gemini Semantic Output Judge]\n        J --> M[Google Search Grounded Verifier]\n    end\n```\n\n### Safety Guarantees:\n- **No Secret Exposure in Untrusted PRs**: Automated PR checks run zero-secret static AST analysis. Live execution requires explicit maintainer gating.\n- **In-Memory Mocking**: The `google.colab` mock is injected only in the kernel memory at runtime. Notebook files on disk are never altered.\n- **Strict Per-Cell Timeouts**: Prevents infinite loops or stalled network requests from blocking CI pipelines.\n- **Cell-Level Retry & Exponential Backoff**: Transient errors (429 rate limits, 503 unavailable, network timeouts) are automatically retried up to 3 times before failing, while non-retryable syntax errors fail immediately.\n\n---\n\n## 3. Evaluation Strategies\n\n| Strategy | Target | Evaluation Mechanism |\n| :--- | :--- | :--- |\n| `exact_or_fuzzy` | Deterministic outputs (token counting, math, static strings). | Normalizes whitespace and verifies exact match or bounded numeric drift (<= 35%). |\n| `schema_validation` | JSON Mode, Structured Outputs, Function Calling. | Validates that output is syntactically valid JSON matching expected structure. |\n| `semantic_llm` | Creative writing, reasoning, explanations, code generation. | Gemini AI Judge evaluates semantic equivalence, scoring as `MATCH`, `SLIGHT_VARIATION`, or `REGRESSION`. |\n| `grounded_factual` | Real-time queries, sports scores, weather, live search. | Gemini fact-checks output against Google Search Grounding to verify freshness and accuracy. |\n| `ignore_output` | Random UUIDs, timestamps, skipped interactive cells. | Marks cell as `SKIPPED` without evaluating output diffs. |\n\n---\n\n## 4. In-Memory Dynamic Model Overriding (`--model <name>`)\n\nTo test entire test suites or individual tutorials against candidate models (e.g. `gemini-3.7-flash`, `gemini-3.1-pro-preview`) without permanently modifying repository notebooks, `nb_tester` integrates an in-memory AST and regex transformer:\n\n```\n                      ┌─────────────────────────────────────┐\n                      │   Original Notebook (.ipynb file)   │\n                      │  (MODEL_ID = \"gemini-4-hydrogen\")   │\n                      └──────────────────┬──────────────────┘\n                                         │ (Deepcopy in memory)\n                                         ▼\n                      ┌─────────────────────────────────────┐\n                      │    ModelOverrideTransformer        │\n                      │  - Rewrites assignments to MODEL_ID │\n                      │  - Rewrites Colab @param dropdowns  │\n                      │  - Generates kernel preamble        │\n                      └──────────────────┬──────────────────┘\n                                         │\n                                         ▼\n                      ┌─────────────────────────────────────┐\n                      │    Ephemeral IPython Kernel         │\n                      │  (MODEL_ID = \"<override_model>\")    │\n                      │  (os.environ[\"MODEL_ID\"] = \"...\")   │\n                      └─────────────────────────────────────┘\n```\n\n### Safety & Integrity Guarantees:\n- **Zero Disk Mutation**: All AST transformations occur exclusively on in-memory `NotebookNode` copies. Original `.ipynb` files on disk are never altered.\n- **Full Assignment Coverage**: Matches single quotes, double quotes, Colab `# @param` forms, type annotations, and chained assignments.\n- **Preamble Injection**: Injects `MODEL_ID` and environment variables before cell 0 to ensure immediate environment readiness.\n\n---\n\n## 5. Observability & Developer Experience\n\n- **Config Centralization**: All models (`SECURITY_AUDITOR_MODEL`, `OUTPUT_JUDGE_MODEL`, `GROUNDED_VERIFIER_MODEL`, `OVERRIDE_MODEL`), timeouts, and thresholds reside in `config.py`.\n- **LLM Observability**: Every single call to Gemini logs the prompt, generation parameters, response, and duration.\n- **Dry-Run Capability**: Every feature can be validated using `--dry-run` without touching network or filesystem state.\n"},"files":{"tools/README.md":"# Gemini API Cookbook Quality Assurance & Linting Tools\n\nThis directory contains standalone tools for formatting, linting, and maintaining Jupyter/Colab notebooks in the [Gemini API Cookbook](https://github.com/google-gemini/cookbook).\n\nThese tools are natively hosted in this repository to provide fast, zero-dependency validation tailored specifically to the Gemini SDK and cookbook style guidelines.\n\n---\n\n## Tools Overview\n\n| Tool | Script | Description |\n| :--- | :--- | :--- |\n| **`nblint`** | `tools/nblint_cli.py` | Lints notebooks for licensing, structure, style, SDK best practices, and model selectors. |\n| **`nbfmt`** | `tools/nbfmt_cli.py` | Automatically formats notebook JSON, standardizes metadata, strips empty cells, and aligns code formatting. |\n| **`readme_links`** | `tools/check_readme_links.py` | Validates that new/modified notebooks are linked in section Table of Contents READMEs. |\n| **`check_all_links`** | `tools/check_all_links.py` | Audits internal paths, anchors, blob URLs, and external links across `.md` and `.ipynb` files. |\n| **`config`** | `tools/config.py` | Central configuration file containing model hierarchies, wordlists, exclusions, and URL rules. |\n\n---\n\n## 1. Quickstart Usage\n\n### Linting Notebooks\n```bash\n# Lint a specific notebook\npython tools/nblint_cli.py quickstarts/Get_started.ipynb\n\n# Lint multiple notebooks or directories\npython tools/nblint_cli.py quickstarts/**/*.ipynb examples/**/*.ipynb\n\n# Perform a dry-run check\npython tools/nblint_cli.py --dry-run quickstarts/Get_started.ipynb\n\n# Specify custom branch or repository\npython tools/nblint_cli.py --repo=google-gemini/cookbook --branch=main path/to/notebook.ipynb\n```\n\n### Formatting Notebooks\n```bash\n# Format a specific notebook (modifies file in place)\npython tools/nbfmt_cli.py quickstarts/Get_started.ipynb\n\n# Test if notebooks are properly formatted (without modifying, returns non-zero on unformatted)\npython tools/nbfmt_cli.py --test quickstarts/**/*.ipynb\n\n# Format all notebooks in the repo\npython tools/nbfmt_cli.py quickstarts/**/*.ipynb examples/**/*.ipynb\n```\n\n### Checking Table of Contents README Links\n```bash\n# Check if a specific notebook is linked in its folder/section README.md\npython tools/check_readme_links.py quickstarts/Get_started.ipynb\n\n# Audit all notebooks in the repo\npython tools/check_readme_links.py --all\n```\n\n### Verifying Internal and External Links\n```bash\n# Validate internal links and anchors on specific files (fast CI check)\npython tools/check_all_links.py quickstarts/Get_started.ipynb README.md\n\n# Validate all git-modified files against upstream/main\npython tools/check_all_links.py --changed\n\n# Full repository audit of all internal relative links and anchor slugs\npython tools/check_all_links.py\n\n# Full repository audit including live external HTTP/HTTPS health checks\npython tools/check_all_links.py --all\n```\n\n---\n\n## 2. Lint Rules Reference\n\n### Python Syntax Rules (`tools/nblint/rules/syntax.py`)\n- **`syntax::code_cell`**: Parses code cells, including `%%time` bodies, with `ast.parse` after neutralizing IPython magics and shell escapes. Other `%%` cell magics are skipped. Reports the cell index and original line of any `SyntaxError`.\n\n### Structure Rules (`tools/nblint/rules/structure.py`)\n- **`structure::copyright`**: Verifies that cell 0 contains a valid Google / Gemini copyright statement (`##### Copyright 2026 Google LLC.`).\n- **`structure::license`**: Verifies that the notebook contains a collapsed Apache 2.0 license code cell with `# @title Licensed under the Apache License`.\n- **`structure::colab_button`**: Checks for the \"Open in Colab\" badge and verifies that its destination URL matches `https://colab.research.google.com/github/<repo>/blob/<branch>/<path>`. Automatically adjusts for redirect stubs.\n- **`structure::next_steps`**: Emits a warning if a closing section is missing. Accepted headings: \"Next steps\", \"What's next\", \"Learn more\" / \"Learning more\", \"Further reading\" / \"Further resources\" or \"Conclusion\".\n\n### Style & Language Rules (`tools/nblint/rules/style.py`)\n- **`style::inclusive_language`**: Flags discouraged terminology (`blacklist`, `whitelist`, `master`, `slave`) and suggests modern alternatives. **Note**: The word `\"native\"` is deliberately allowed because terms like *\"native audio\"*, *\"native TTS\"*, and *\"native multimodal\"* are standard Gemini API features.\n- **`style::second_person`**: Ensures narrative explanations in markdown use second person (*you*) rather than first person (*we*). Prompt strings, quoted examples, and code comments are ignored.\n- **`style::line_length`**: Warns when code lines exceed 100 characters (ignoring URLs, form annotations, and long multiline strings).\n\n### Gemini SDK & API Best Practices (`tools/nblint/rules/gemini.py`)\n- **`gemini::pip_magic`**: Enforces `%pip install` instead of `!pip install` for reliable kernel-level package installation.\n- **`gemini::sdk_package`**: Enforces the official `from google import genai` (`google-genai`) SDK, flagging deprecated `google.generativeai`.\n- **`gemini::api_key_secret`**: Checks that notebooks retrieve API keys from `userdata.get('GEMINI_API_KEY')` rather than the legacy `GOOGLE_API_KEY` secret.\n- **`gemini::hardcoded_api_key`**: Scans all cells for accidental plaintext Google/Gemini API keys (legacy `AIza...` and new `AQ.Ab8...` formats) to prevent credential leakage.\n\n### Model Selector Validation (`tools/nblint/rules/model_selector.py`)\n- **`gemini::model_selector`**:\n  - Verifies that model selectors use the canonical Colab form pattern:\n    ```python\n    MODEL_ID = \"gemini-3.7-flash\" # @param [\"gemini-3.1-pro-preview\", \"gemini-3.7-flash\", \"gemini-3.5-flash-lite\"] {\"allow-input\":true, isTemplate: true}\n    ```\n  - Verifies that the default assigned model exists in the option list.\n  - Verifies that models in the list are sorted in logical order from most capable to least capable: **current generation (Pro $\\rightarrow$ Flash $\\rightarrow$ Flash-Lite)**, followed by **previous generation (e.g. Gemini 3.x)**.\n\n---\n\n## 3. Configuration & Exclusions\n\nAll configurable settings are consolidated in `tools/config.py`:\n- **`EXCLUDED_NOTEBOOKS`**: List of files skipped during automated lint runs (e.g. `quickstarts/Template.ipynb`).\n- **`REDIRECT_KEYWORDS`**: Keywords used to automatically detect redirection stubs (e.g. `gemini-robotics-er.ipynb`) and apply lenient rules.\n- **`get_model_sort_key(model_name)`**: Ranking algorithm for model selector ordering.\n- **`INCLUSIVE_LANGUAGE_WORDLIST`**: Mapping of discouraged terms to replacements.\n","tools/link_checker/Design.md":"# Architecture & Design: Cookbook Link Checker (`tools/check_all_links.py`)\n\n## 1. Overview & Objectives\n\nThe **Cookbook Link Checker** is an automated quality gate designed to prevent broken, dead, or misdirected links from entering the `google-gemini/cookbook` repository. It audits both Markdown documentation (`.md`) and Jupyter Notebooks (`.ipynb`), providing sub-second validation for Pull Requests and comprehensive health checks for scheduled maintenance.\n\n### Primary Goals:\n1. **Zero Broken Links at PR Merge**: Catch renamed notebooks, deleted files, invalid relative paths, and broken anchor links before merging.\n2. **Sub-Second CI Runtime**: Ensure that PR checks on modified files execute in `<1-2s` without depending on external network calls.\n3. **Deep Anchor Validation**: Validate `#anchor-name` targets both in-page and cross-file, matching GitHub's Markdown slugification rules and HTML `<a name=\"...\">` tags.\n4. **Seamless Integration**: Native Python standard library implementation with zero external dependencies (no `requests`, `beautifulsoup4`, or `curl` required).\n\n---\n\n## 2. Architecture & Scanning Pipeline\n\n```mermaid\nflowchart TD\n    A[\"CLI / CI Trigger\"] --> B[\"Target File Resolution<br/>(explicit paths, --changed, or full repo)\"]\n    B --> C[\"Link Extraction<br/>(Markdown [text](url) & HTML <a href=...>)\"]\n    C --> D{\"Scheme & Pattern Filter\"}\n    D -->|\"data:, mailto:, tel:, javascript:\"| E[\"Ignored / Skipped\"]\n    D -->|\"Blob URL: github.com/.../blob/main/...\"| F[\"Local Disk Path Resolver\"]\n    D -->|\"Internal Relative Path<br/>(../path.ipynb#heading)\"| G[\"Path Traversal & Anchor Checker\"]\n    D -->|\"External HTTP/HTTPS<br/>(when --all enabled)\"| H[\"Concurrent Worker Pool<br/>(ThreadPoolExecutor)\"]\n    \n    F --> I[\"Anchor & File Validator\"]\n    G --> I\n    I --> J[\"In-Memory Anchor Cache<br/>(_anchors_cache)\"]\n    \n    H --> K{\"HEAD Status\"}\n    K -->|\"200-399\"| L[\"Valid\"]\n    K -->|\"403 / 405\"| M[\"Fallback to GET\"]\n    K -->|\"404 / 500 / Timeout\"| N[\"Report Broken\"]\n    \n    I --> O[\"Aggregation & Exit Code\"]\n    N --> O\n    L --> O\n```\n\n---\n\n## 3. Link Categories & Resolution Rules\n\n### 3.1 Internal Relative Links (`./...`, `../...`)\n- Resolves paths relative to the parent directory of the source file.\n- Guards against path traversal vulnerabilities by enforcing `target_path.relative_to(repo_root)`.\n- Verifies physical file existence on disk.\n\n### 3.2 GitHub Repository Blob URLs (`https://github.com/google-gemini/cookbook/blob/main/...`)\n- Contributors often write absolute GitHub blob URLs pointing to other cookbook files.\n- The tool intercepts links starting with `https://github.com/google-gemini/cookbook/blob/main/` and maps them directly to the local clone working tree.\n- Catches broken links introduced during renames even if the external branch has not yet been pushed or merged.\n\n### 3.3 Anchor Fragment Verification (`#...`)\n- **Colab UI Fragments**: `#scrollTo=...` is recognized as a Google Colab cell identifier and validated against cell IDs or gracefully allowed.\n- **In-Page Anchors**: `#heading-title` in `README.md` validates that `heading-title` exists as a slugified heading or HTML `<a name=\"...\">` in `README.md`.\n- **Cross-File Anchors**: `quickstarts/Get_started.ipynb#audio` validates that `quickstarts/Get_started.ipynb` exists and contains an anchor or heading slug matching `audio`.\n- **Anchor Caching**: Targets are parsed once and cached in `_anchors_cache` to keep multi-thousand link audits under 2 seconds.\n\n### 3.4 Data URIs & Media Exclusions\n- Inline image data (`![img](data:image/png;base64,...)`) is excluded via `re.compile(r\"^data:\")` to prevent massive base64 string dumps in error logs.\n- Documentation template placeholders (`URL`, `TODO`) are whitelisted via `LINK_CHECKER_EXCLUDED_TARGETS` in `tools/config.py`.\n\n### 3.5 External HTTP/HTTPS Links (`--all`)\n- Uses `concurrent.futures.ThreadPoolExecutor(max_workers=16)` for parallel HTTP verification.\n- Dispatches HTTP `HEAD` with standard browser `User-Agent`.\n- Automatically retries with HTTP `GET` if the target server rejects `HEAD` with `405 Method Not Allowed` or `403 Forbidden`.\n- Bypasses ignored domains (`localhost`, `127.0.0.1`, Google API endpoints requiring API keys).\n\n---\n\n## 4. GitHub Actions CI Integration\n\nThe workflow `.github/workflows/link_checker.yml` operates in three modes:\n\n1. **Pull Request Mode (`pull_request`)**:\n   - Computes changed files via `git merge-base HEAD ${{ github.event.pull_request.base.sha }}`.\n   - Audits only modified `.ipynb` and `.md` files in `--internal-only` mode.\n   - Completes in `<2` seconds, blocking regressions with zero flaky external network failures.\n2. **Weekly Scheduled Health Check (`schedule: cron '0 8 * * 1'`)**:\n   - Runs on Mondays at 08:00 UTC.\n   - Audits all internal paths AND performs concurrent external HTTP validation across all URLs.\n3. **Manual Dispatch (`workflow_dispatch`)**:\n   - Enables maintainers to run full audits on demand with an optional `check_external` boolean flag.\n","tools/Design.md":"# Gemini API Cookbook Quality Assurance Tools: Architecture & Design\n\n## 1. Background & Motivation\n\nPreviously, the Gemini API Cookbook's CI and developer workflows relied on the external package `tensorflow-docs` (`github.com/tensorflow/docs`) for notebook formatting (`nbfmt`) and linting (`nblint`).\n\nThis legacy setup created several critical operational problems:\n1. **External Dependency**: CI had to install `git+https://github.com/tensorflow/docs` on every workflow run. Any changes or fixes required modifying a separate repository.\n2. **False Positives on \"native\"**: `tensorflow/docs` included `\"native\": \"built-in\"` in its inclusive language wordlist. In the Gemini ecosystem, terms like *\"native audio\"*, *\"native TTS\"*, *\"native multimodal output\"*, and model IDs like `gemini-2.5-flash-native-audio-preview` are official terminology, causing CI to fail on valid PRs.\n3. **Overly Strict First-Person Flags**: The legacy linter flagged words like `\"we\"` inside code comments and string parameters (e.g. `text_prompt = \"we can see the stage...\"`).\n4. **Irrelevant Legacy Rules**: Checks for TensorFlow 1.x `r1/` directories and `tfhub.dev` buttons had to be manually excluded in CI commands.\n5. **Lack of Gemini-Specific Checks**: Common review issues—such as using `!pip` instead of `%pip`, legacy `google.generativeai` imports, `GOOGLE_API_KEY` vs `GEMINI_API_KEY`, model selector ordering, and hardcoded API keys—had to be caught manually by maintainers.\n\n## 2. Design Principles & Goals\n\n1. **Zero External Tool Dependencies**: Implemented using standard Python libraries (`json`, `pathlib`, `re`, `logging`, `argparse`, `dataclasses`).\n2. **Centralized Configuration**: All configurable parameters, model order ranks, excluded files, and wordlists reside in `tools/config.py`.\n3. **Modular Rule Architecture**: Separate rule modules for structure, style, SDK best practices, and model selector formatting.\n4. **First-Class Support for Special Notebooks**:\n   - **Template Notebook**: Explicitly excluded from full strictness tests.\n   - **Redirect Stubs**: Auto-detected via cell count and content keywords, skipping full content and Colab button mismatch failures.\n5. **Comprehensive Logging & Dry-Run**: Detailed INFO and DEBUG logs, and full `--dry-run` and `--test` support for safe local and CI testing.\n\n## 3. Directory Layout\n\n```\ntools/\n├── __init__.py\n├── config.py                 # Centralized configuration & model hierarchies\n├── nblint/                   # Linter core & rule implementations\n│   ├── __init__.py\n│   ├── linter.py             # Linter execution engine & result aggregation\n│   └── rules/\n│       ├── __init__.py\n│       ├── structure.py      # Copyright, License, Colab button, Next steps\n│       ├── style.py          # Inclusive language (no native), Second person\n│       ├── gemini.py         # %pip vs !pip, google-genai SDK, GEMINI_API_KEY, no leaks\n│       └── model_selector.py # @param Colab form & model ordering validation\n├── nbfmt/                    # Formatter core\n│   ├── __init__.py\n│   └── formatter.py          # JSON normalization, metadata & cell cleaning\n├── nblint_cli.py             # CLI entrypoint for linting\n├── nbfmt_cli.py             # CLI entrypoint for formatting\n├── README.md                 # User guide and CLI reference\n└── Design.md                 # Architecture and design rationale (this document)\n```\n\n## 4. Model Hierarchy & Ordering Logic\n\nIn `tools/config.py`, the model selector rule sorts models using `get_model_sort_key()`:\n- **Capability Tiers**: Models are ordered from most capable to least capable: Pro $\\rightarrow$ Flash $\\rightarrow$ Flash-Lite $\\rightarrow$ Domain-specific (Live/Veo/Imagen/Lyria).\n- **Generations**: Current generation models (e.g. Gemini 4.x) precede previous generations (e.g. Gemini 3.x).\n","tools/nb_tester/README.md":"# 🧪 Gemini API Cookbook Notebook Testing & Regression Suite\n\nAn automated, security-gated test runner and semantic regression evaluator designed specifically for the Jupyter/Colab notebooks in the [Gemini API Cookbook](https://github.com/google-gemini/cookbook).\n\n---\n\n## 🌟 Key Features\n\n1. **🔒 Multi-Layer Security Architecture (Preventing RCE & Key Theft)**:\n   - **Level 1 (Static AST Scanner)**: Fast, zero-secret AST checks for forbidden system calls, reverse shells, and raw environment dumps.\n   - **Level 2 (Gemini AI Security Auditor)**: Semantic code review with structured JSON output before any code execution to detect subtle backdoors, malicious `%pip` dependencies, or data exfiltration.\n   - **Zero-Disk-Tampering Colab Mock**: Injects a virtual `google.colab.userdata` module into the kernel namespace in memory, keeping notebooks clean and keys secure.\n2. **⚖️ Semantic Output Regression Judging**:\n   - Compares newly generated outputs with the saved reference outputs in the repository.\n   - Uses Gemini AI Judge to separate normal non-deterministic phrasing differences (`SLIGHT_VARIATION`) from true broken answers or hallucinations (`REGRESSION`).\n3. **🌐 Google Search Grounding Verification**:\n   - For real-time and time-evolving queries (e.g. sports scores, weather, current events), uses Gemini with the Google Search tool to double-check that new answers are factually true today.\n4. **📋 Declarative Rules & Exception Registry (`rules/default_rules.yaml`)**:\n   - Easily configure cell-level actions (e.g. skipping interactive `input()` cells) and per-notebook timeouts.\n5. **🎯 Family-Aware Dynamic Model Identifier Override (`--model <name>`)**:\n   - Test the entire cookbook (or specific notebooks) against candidate or pre-release models (e.g. `gemini-4-hydrogen`, `gemini-3.8-flash`, `gemini-3.1-pro-preview`) by dynamically overriding `MODEL_ID` in memory across compatible cells without touching disk.\n   - Automatically preserves specialized non-text models (`-live`, `-tts`, `-image`, `embedding`, `veo`, `lyria`, `transcribe`) unless the override model itself belongs to that same model family.\n6. **📊 CI & Pull Request Integration**:\n   - Generates persistent JSON reports under `reports/` and auto-appends formatted Markdown tables to `$GITHUB_STEP_SUMMARY`.\n   - Returns clean exit codes (`0` on pass, `1` on failure) for automated gating.\n7. **🔍 Dry-Run Mode**:\n   - Test rule configurations, AST checks, model overrides, and syntax parsing without altering files, spinning up kernels, or consuming API tokens.\n8. **🔁 Automatic Cell-Level Retry & Exponential Backoff**:\n   - Automatically retries failed cells (up to 3 times by default with exponential backoff) on transient API errors (429, 503, timeouts) before failing, preventing flaky CI runs while skipping non-retryable syntax errors. Configurable via `--max-retries` CLI flag or `rules/default_rules.yaml`.\n\n---\n\n## 🛠️ System Prerequisites (Local Execution)\n\nIn Google Colab, `ffmpeg`, `jq`, and `curl` are pre-installed in the default runtime container (and `poppler-utils` is installed via `!apt-get install -y -q poppler-utils` inside `quickstarts/PDF_Files.ipynb`).\n\nWhen running `tools/nb_tester` locally on a Linux/macOS workstation or headless CI runner (where notebooks do not execute as `root`), install the following system packages first so audio, video, PDF (`pdf2image` / `pdftoppm`), and REST (`curl` + `jq`) notebooks execute cleanly:\n\n```bash\n# Ubuntu / Debian / gLinux\nsudo apt-get update && sudo apt-get install -y ffmpeg poppler-utils jq curl\n```\n\n---\n\n## 🚀 Quickstart & Usage\n\n### 1. Dry-Run Mode (Safe simulation)\n```bash\npython3 -m tools.nb_tester.cli --notebook quickstarts/Counting_Tokens.ipynb --dry-run\n```\n\n### 2. Security Audit Only (No code execution)\n```bash\npython3 -m tools.nb_tester.cli --notebook quickstarts/Prompting.ipynb --security-only\n```\n\n### 3. Test a Single Notebook with Live Execution & AI Judge\n```bash\nexport GEMINI_API_KEY=\"your-api-key\"\npython3 -m tools.nb_tester.cli --notebook quickstarts/Counting_Tokens.ipynb\n```\n\n### 4. Test Only Changed Notebooks in a PR / Git Branch\n```bash\npython3 -m tools.nb_tester.cli --changed\n```\n\n### 5. Test Notebooks with Dynamic Model Override\n```bash\n# Run a specific quickstart against a candidate/preview model\npython3 -m tools.nb_tester.cli --notebook quickstarts/Get_started_thinking.ipynb --model gemini-3.1-pro-preview\n\n# Run all quickstarts with model override in parallel\npython3 -m tools.nb_tester.cli --all --model gemini-3.7-flash --workers 4\n```\n\n### 6. Run Full Suite in Parallel\n```bash\npython3 -m tools.nb_tester.cli --all --workers 4\n```\n\n---\n\n## ⚙️ Configuration & Exception Rules\n\nRules are declared in `tools/nb_tester/rules/default_rules.yaml`.\n\n```yaml\nglobal_defaults:\n  cell_timeout_sec: 90\n  notebook_timeout_sec: 600\n  default_strategy: \"semantic_llm\"\n\nnotebooks:\n  quickstarts/Grounding.ipynb:\n    cells:\n      - match: \"client.models.generate_content\"\n        strategy: \"grounded_factual\"\n        description: \"Verify dynamic search output using Google Search\"\n\n  quickstarts/Interactive_Chat.ipynb:\n    cells:\n      - match: \"input(\"\n        action: \"skip\"\n        reason: \"Interactive user input not supported in headless CI\"\n```\n\n---\n\n## 🏗️ Architecture & Modules\n\n```\ntools/nb_tester/\n├── config.py             # Centralized models, timeouts, and GEMINI_API_KEY resolution\n├── logger.py             # Structured logging with complete LLM prompt/response tracking\n├── security_scanner.py   # Level 1: Deterministic AST & regex scanner\n├── ai_security_auditor.py# Level 2: Gemini AI Semantic Security Auditor\n├── rules.py              # Declarative rules engine and matcher\n├── model_override.py     # In-memory MODEL_ID override transformer & preamble injector\n├── executor.py           # nbclient kernel executor with in-memory Colab mock\n├── comparator.py         # Output snapshot extractor and strategy router\n├── llm_judge.py          # Level 3: Semantic output regression judge\n├── grounded_verifier.py  # Real-time fact-checking via Google Search Grounding\n├── reporter.py           # Multi-format report builder (JSON, Step Summary, Terminal)\n├── cli.py                # Command-line interface entry point\n└── rules/\n    └── default_rules.yaml# Default rule definitions and exceptions\n```\n","tools/nb_tester/rules/default_rules.yaml":"# Copyright 2026 Google LLC\n# Default Testing & Exception Rules for Gemini API Cookbook Notebooks\n\n# Global defaults across all notebooks unless overridden\nglobal_defaults:\n  cell_timeout_sec: 240\n  notebook_timeout_sec: 1200\n  default_strategy: \"semantic_llm\"\n  cell_max_retries: 3\n  cell_retry_backoff_sec: 2.0\n\n# Specific notebook overrides\nnotebooks:\n  quickstarts/Counting_Tokens.ipynb:\n    cell_timeout_sec: 60\n    cells:\n      - match: \"client.models.count_tokens\"\n        strategy: \"exact_or_fuzzy\"\n        description: \"Token counting outputs are deterministic integers\"\n\n  quickstarts/Grounding.ipynb:\n    cells:\n      - match: \"client.models.generate_content\"\n        strategy: \"grounded_factual\"\n        description: \"Live search grounded responses may evolve over time; double check with Google Search\"\n\n  quickstarts/Search_Grounding.ipynb:\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1200\n    allow_dynamic_exec: true\n    allow_security_demo: true\n    cells:\n      - match: \"client.models.generate_content\"\n        strategy: \"grounded_factual\"\n        description: \"Verify factual correctness of live Google Search results\"\n\n  quickstarts/JSON_mode.ipynb:\n    cells:\n      - match: \"response_mime_type=\\\"application/json\\\"\"\n        strategy: \"schema_validation\"\n        description: \"Validates JSON structure conformance\"\n\n  quickstarts/Interactive_Chat.ipynb:\n    cells:\n      - match: \"input(\"\n        action: \"skip\"\n        reason: \"Interactive user input cell cannot execute in headless CI\"\n\n  quickstarts/Authentication_with_OAuth.ipynb:\n    skip_notebook: true\n    skip_reason: \"Requires interactive browser OAuth login flow\"\n\n  quickstarts/Webhooks.ipynb:\n    skip_notebook: true\n    skip_reason: \"Requires live webhook receiver server endpoint\"\n\n  quickstarts/Get_started_Veo.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1500\n    description: \"Video generation takes longer than text generation\"\n\n  quickstarts/Get_started_Veo_REST.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1500\n    description: \"REST Veo video generation and polling\"\n\n  quickstarts/Batch_mode.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1800\n    description: \"Asynchronous Batch API job polling can take 5-15 minutes\"\n\n  quickstarts/File_API.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1500\n    description: \"Uploads and processes a 45-minute video via File API\"\n\n  quickstarts/Get_started_Lyria.ipynb:\n    long_running: true\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1200\n    description: \"Real-time Lyria music generation streaming\"\n\n  quickstarts/Tuning.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1800\n    description: \"Model tuning job creation and training loop\"\n\n  quickstarts/Get_started_Deep_Research.ipynb:\n    long_running: true\n    cell_timeout_sec: 1800\n    notebook_timeout_sec: 2400\n    description: \"Deep Research queries can take up to 30+ minutes\"\n\n  quickstarts/Get_Started_Nano_Banana.ipynb:\n    cell_timeout_sec: 180\n    notebook_timeout_sec: 1800\n    description: \"Image generation and multi-turn image editing\"\n\n  quickstarts/Get_started_thinking.ipynb:\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1800\n    description: \"Extended thinking generation chains can take up to 10 minutes per cell\"\n\n  quickstarts/Get_started_thinking_REST.ipynb:\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1200\n    description: \"Thinking REST endpoint multi-turn analysis\"\n\n  quickstarts/Get_started_Omni.ipynb:\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1200\n    description: \"Omni multimodal model processing\"\n\n  quickstarts/Video_understanding.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1500\n    description: \"Video upload, processing, and multi-turn frame analysis\"\n\n  quickstarts/Inference_tiers.ipynb:\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1200\n    description: \"Multi-tier model benchmarking and latency comparison\"\n\n  quickstarts/Get_started.ipynb:\n    cell_timeout_sec: 300\n    notebook_timeout_sec: 1200\n    description: \"Full tour of multimodal features across large files\"\n\n  examples/Virtual_Try_On.ipynb:\n    skip_notebook: true\n    skip_reason: \"Requires interactive Colab Vertex AI auth (auth.authenticate_user)\"\n\n  examples/Google_IO2025_Live_Coding.ipynb:\n    skip_notebook: true\n    skip_reason: \"Historical event notebook kept frozen with original Google I/O 2025 models\"\n\n  examples/Book_illustration.ipynb:\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1800\n    description: \"Multimodal audio, TTS, image generation, and MoviePy mix\"\n\n  examples/gemini_google_adk_model_guardrails.ipynb:\n    allow_security_demo: true\n    description: \"Demonstrates model guardrails against prompt injection and backdoors\"\n\n  examples/LiveAPI_plotting_and_mapping.ipynb:\n    allow_dynamic_exec: true\n    allow_security_demo: true\n    description: \"Demonstrates live plotting and mapping using code execution tools\"\n\n  examples/prompting/Basic_Code_Generation.ipynb:\n    allow_dynamic_exec: true\n    allow_security_demo: true\n    description: \"Demonstrates generating and executing Python code via exec()\"\n","tools/nb_tester/Design.md":"# 📐 Design Document: Notebook Automated Testing, Security & Regression Suite\n\n## 1. Context & Objectives\n\nThe **Gemini API Cookbook** is a central public repository of Python/Jupyter tutorials. Maintaining quality across rapid model releases and SDK iterations introduces two fundamental challenges:\n1. **Security in Open-Source PRs**: Untrusted pull requests from public contributors could execute arbitrary code (RCE) or exfiltrate repo secrets/tokens (`GEMINI_API_KEY`).\n2. **Non-Deterministic Semantic Regressions**: Code might run without raising an exception (exit code 0), but the model's output could regress into low-quality answers, hallucinations, or broken formats.\n3. **Dynamic & Evolving Data**: Grounded search queries (e.g. sports scores, weather) will naturally change over time and require factual verification rather than static string matching.\n\n---\n\n## 2. Threat Model & Multi-Layer Safety Defense\n\n```mermaid\nflowchart TD\n    subgraph Gate1 [Gate 1: Static AST &amp; Regex Scanner]\n        A[PR / Target Notebook] --> B[Parse Code Cells to AST]\n        B --> C{Forbidden calls? eval, exec, os.environ dump}\n        C -- Yes --> D[🚨 Hard Block - Critical Finding]\n        C -- No --> Gate2\n    end\n\n    subgraph Gate2 [Gate 2: Semantic AI Security Auditor]\n        Gate2[Gemini AI Security Model] --> E[Analyze code logic &amp; external URLs]\n        E --> F{Risk Score &lt;= 3 and Verdict == SAFE?}\n        F -- No --> G[🚨 Security Block - Human Review Required]\n        F -- Yes --> Gate3\n    end\n\n    subgraph Gate3 [Gate 3: Isolated Execution &amp; Colab Mock]\n        Gate3[Ephemeral Kernel] --> H[Inject in-memory google.colab.userdata]\n        H --> I[Execute cell-by-cell with timeouts]\n        I --> J[Capture Outputs &amp; Tracebacks]\n    end\n\n    subgraph Gate4 [Gate 4: Output Evaluation &amp; Fact-Checking]\n        J --> K[Exact / Fuzzy / Schema Check]\n        J --> L[Gemini Semantic Output Judge]\n        J --> M[Google Search Grounded Verifier]\n    end\n```\n\n### Safety Guarantees:\n- **No Secret Exposure in Untrusted PRs**: Automated PR checks run zero-secret static AST analysis. Live execution requires explicit maintainer gating.\n- **In-Memory Mocking**: The `google.colab` mock is injected only in the kernel memory at runtime. Notebook files on disk are never altered.\n- **Strict Per-Cell Timeouts**: Prevents infinite loops or stalled network requests from blocking CI pipelines.\n- **Cell-Level Retry & Exponential Backoff**: Transient errors (429 rate limits, 503 unavailable, network timeouts) are automatically retried up to 3 times before failing, while non-retryable syntax errors fail immediately.\n\n---\n\n## 3. Evaluation Strategies\n\n| Strategy | Target | Evaluation Mechanism |\n| :--- | :--- | :--- |\n| `exact_or_fuzzy` | Deterministic outputs (token counting, math, static strings). | Normalizes whitespace and verifies exact match or bounded numeric drift (<= 35%). |\n| `schema_validation` | JSON Mode, Structured Outputs, Function Calling. | Validates that output is syntactically valid JSON matching expected structure. |\n| `semantic_llm` | Creative writing, reasoning, explanations, code generation. | Gemini AI Judge evaluates semantic equivalence, scoring as `MATCH`, `SLIGHT_VARIATION`, or `REGRESSION`. |\n| `grounded_factual` | Real-time queries, sports scores, weather, live search. | Gemini fact-checks output against Google Search Grounding to verify freshness and accuracy. |\n| `ignore_output` | Random UUIDs, timestamps, skipped interactive cells. | Marks cell as `SKIPPED` without evaluating output diffs. |\n\n---\n\n## 4. In-Memory Dynamic Model Overriding (`--model <name>`)\n\nTo test entire test suites or individual tutorials against candidate models (e.g. `gemini-3.7-flash`, `gemini-3.1-pro-preview`) without permanently modifying repository notebooks, `nb_tester` integrates an in-memory AST and regex transformer:\n\n```\n                      ┌─────────────────────────────────────┐\n                      │   Original Notebook (.ipynb file)   │\n                      │  (MODEL_ID = \"gemini-4-hydrogen\")   │\n                      └──────────────────┬──────────────────┘\n                                         │ (Deepcopy in memory)\n                                         ▼\n                      ┌─────────────────────────────────────┐\n                      │    ModelOverrideTransformer        │\n                      │  - Rewrites assignments to MODEL_ID │\n                      │  - Rewrites Colab @param dropdowns  │\n                      │  - Generates kernel preamble        │\n                      └──────────────────┬──────────────────┘\n                                         │\n                                         ▼\n                      ┌─────────────────────────────────────┐\n                      │    Ephemeral IPython Kernel         │\n                      │  (MODEL_ID = \"<override_model>\")    │\n                      │  (os.environ[\"MODEL_ID\"] = \"...\")   │\n                      └─────────────────────────────────────┘\n```\n\n### Safety & Integrity Guarantees:\n- **Zero Disk Mutation**: All AST transformations occur exclusively on in-memory `NotebookNode` copies. Original `.ipynb` files on disk are never altered.\n- **Full Assignment Coverage**: Matches single quotes, double quotes, Colab `# @param` forms, type annotations, and chained assignments.\n- **Preamble Injection**: Injects `MODEL_ID` and environment variables before cell 0 to ensure immediate environment readiness.\n\n---\n\n## 5. Observability & Developer Experience\n\n- **Config Centralization**: All models (`SECURITY_AUDITOR_MODEL`, `OUTPUT_JUDGE_MODEL`, `GROUNDED_VERIFIER_MODEL`, `OVERRIDE_MODEL`), timeouts, and thresholds reside in `config.py`.\n- **LLM Observability**: Every single call to Gemini logs the prompt, generation parameters, response, and duration.\n- **Dry-Run Capability**: Every feature can be validated using `--dry-run` without touching network or filesystem state.\n"},"items":[{"name":"Design.md","path":"tools/Design.md","rawUrl":"https://raw.githubusercontent.com/google-gemini/cookbook/HEAD/tools/Design.md","title":"tools - UI Design System & Style Tokens","category":"project-spec","format":"markdown","content":"# Gemini API Cookbook Quality Assurance Tools: Architecture & Design\n\n## 1. Background & Motivation\n\nPreviously, the Gemini API Cookbook's CI and developer workflows relied on the external package `tensorflow-docs` (`github.com/tensorflow/docs`) for notebook formatting (`nbfmt`) and linting (`nblint`).\n\nThis legacy setup created several critical operational problems:\n1. **External Dependency**: CI had to install `git+https://github.com/tensorflow/docs` on every workflow run. Any changes or fixes required modifying a separate repository.\n2. **False Positives on \"native\"**: `tensorflow/docs` included `\"native\": \"built-in\"` in its inclusive language wordlist. In the Gemini ecosystem, terms like *\"native audio\"*, *\"native TTS\"*, *\"native multimodal output\"*, and model IDs like `gemini-2.5-flash-native-audio-preview` are official terminology, causing CI to fail on valid PRs.\n3. **Overly Strict First-Person Flags**: The legacy linter flagged words like `\"we\"` inside code comments and string parameters (e.g. `text_prompt = \"we can see the stage...\"`).\n4. **Irrelevant Legacy Rules**: Checks for TensorFlow 1.x `r1/` directories and `tfhub.dev` buttons had to be manually excluded in CI commands.\n5. **Lack of Gemini-Specific Checks**: Common review issues—such as using `!pip` instead of `%pip`, legacy `google.generativeai` imports, `GOOGLE_API_KEY` vs `GEMINI_API_KEY`, model selector ordering, and hardcoded API keys—had to be caught manually by maintainers.\n\n## 2. Design Principles & Goals\n\n1. **Zero External Tool Dependencies**: Implemented using standard Python libraries (`json`, `pathlib`, `re`, `logging`, `argparse`, `dataclasses`).\n2. **Centralized Configuration**: All configurable parameters, model order ranks, excluded files, and wordlists reside in `tools/config.py`.\n3. **Modular Rule Architecture**: Separate rule modules for structure, style, SDK best practices, and model selector formatting.\n4. **First-Class Support for Special Notebooks**:\n   - **Template Notebook**: Explicitly excluded from full strictness tests.\n   - **Redirect Stubs**: Auto-detected via cell count and content keywords, skipping full content and Colab button mismatch failures.\n5. **Comprehensive Logging & Dry-Run**: Detailed INFO and DEBUG logs, and full `--dry-run` and `--test` support for safe local and CI testing.\n\n## 3. Directory Layout\n\n```\ntools/\n├── __init__.py\n├── config.py                 # Centralized configuration & model hierarchies\n├── nblint/                   # Linter core & rule implementations\n│   ├── __init__.py\n│   ├── linter.py             # Linter execution engine & result aggregation\n│   └── rules/\n│       ├── __init__.py\n│       ├── structure.py      # Copyright, License, Colab button, Next steps\n│       ├── style.py          # Inclusive language (no native), Second person\n│       ├── gemini.py         # %pip vs !pip, google-genai SDK, GEMINI_API_KEY, no leaks\n│       └── model_selector.py # @param Colab form & model ordering validation\n├── nbfmt/                    # Formatter core\n│   ├── __init__.py\n│   └── formatter.py          # JSON normalization, metadata & cell cleaning\n├── nblint_cli.py             # CLI entrypoint for linting\n├── nbfmt_cli.py             # CLI entrypoint for formatting\n├── README.md                 # User guide and CLI reference\n└── Design.md                 # Architecture and design rationale (this document)\n```\n\n## 4. Model Hierarchy & Ordering Logic\n\nIn `tools/config.py`, the model selector rule sorts models using `get_model_sort_key()`:\n- **Capability Tiers**: Models are ordered from most capable to least capable: Pro $\\rightarrow$ Flash $\\rightarrow$ Flash-Lite $\\rightarrow$ Domain-specific (Live/Veo/Imagen/Lyria).\n- **Generations**: Current generation models (e.g. Gemini 4.x) precede previous generations (e.g. Gemini 3.x).\n","isInternal":false,"tokens":906,"sizeBytes":3949},{"name":"Design.md","path":"tools/link_checker/Design.md","rawUrl":"https://raw.githubusercontent.com/google-gemini/cookbook/HEAD/tools/link_checker/Design.md","title":"Link_checker Skill","category":"anthropic-skill","format":"markdown","content":"# Architecture & Design: Cookbook Link Checker (`tools/check_all_links.py`)\n\n## 1. Overview & Objectives\n\nThe **Cookbook Link Checker** is an automated quality gate designed to prevent broken, dead, or misdirected links from entering the `google-gemini/cookbook` repository. It audits both Markdown documentation (`.md`) and Jupyter Notebooks (`.ipynb`), providing sub-second validation for Pull Requests and comprehensive health checks for scheduled maintenance.\n\n### Primary Goals:\n1. **Zero Broken Links at PR Merge**: Catch renamed notebooks, deleted files, invalid relative paths, and broken anchor links before merging.\n2. **Sub-Second CI Runtime**: Ensure that PR checks on modified files execute in `<1-2s` without depending on external network calls.\n3. **Deep Anchor Validation**: Validate `#anchor-name` targets both in-page and cross-file, matching GitHub's Markdown slugification rules and HTML `<a name=\"...\">` tags.\n4. **Seamless Integration**: Native Python standard library implementation with zero external dependencies (no `requests`, `beautifulsoup4`, or `curl` required).\n\n---\n\n## 2. Architecture & Scanning Pipeline\n\n```mermaid\nflowchart TD\n    A[\"CLI / CI Trigger\"] --> B[\"Target File Resolution<br/>(explicit paths, --changed, or full repo)\"]\n    B --> C[\"Link Extraction<br/>(Markdown [text](url) & HTML <a href=...>)\"]\n    C --> D{\"Scheme & Pattern Filter\"}\n    D -->|\"data:, mailto:, tel:, javascript:\"| E[\"Ignored / Skipped\"]\n    D -->|\"Blob URL: github.com/.../blob/main/...\"| F[\"Local Disk Path Resolver\"]\n    D -->|\"Internal Relative Path<br/>(../path.ipynb#heading)\"| G[\"Path Traversal & Anchor Checker\"]\n    D -->|\"External HTTP/HTTPS<br/>(when --all enabled)\"| H[\"Concurrent Worker Pool<br/>(ThreadPoolExecutor)\"]\n    \n    F --> I[\"Anchor & File Validator\"]\n    G --> I\n    I --> J[\"In-Memory Anchor Cache<br/>(_anchors_cache)\"]\n    \n    H --> K{\"HEAD Status\"}\n    K -->|\"200-399\"| L[\"Valid\"]\n    K -->|\"403 / 405\"| M[\"Fallback to GET\"]\n    K -->|\"404 / 500 / Timeout\"| N[\"Report Broken\"]\n    \n    I --> O[\"Aggregation & Exit Code\"]\n    N --> O\n    L --> O\n```\n\n---\n\n## 3. Link Categories & Resolution Rules\n\n### 3.1 Internal Relative Links (`./...`, `../...`)\n- Resolves paths relative to the parent directory of the source file.\n- Guards against path traversal vulnerabilities by enforcing `target_path.relative_to(repo_root)`.\n- Verifies physical file existence on disk.\n\n### 3.2 GitHub Repository Blob URLs (`https://github.com/google-gemini/cookbook/blob/main/...`)\n- Contributors often write absolute GitHub blob URLs pointing to other cookbook files.\n- The tool intercepts links starting with `https://github.com/google-gemini/cookbook/blob/main/` and maps them directly to the local clone working tree.\n- Catches broken links introduced during renames even if the external branch has not yet been pushed or merged.\n\n### 3.3 Anchor Fragment Verification (`#...`)\n- **Colab UI Fragments**: `#scrollTo=...` is recognized as a Google Colab cell identifier and validated against cell IDs or gracefully allowed.\n- **In-Page Anchors**: `#heading-title` in `README.md` validates that `heading-title` exists as a slugified heading or HTML `<a name=\"...\">` in `README.md`.\n- **Cross-File Anchors**: `quickstarts/Get_started.ipynb#audio` validates that `quickstarts/Get_started.ipynb` exists and contains an anchor or heading slug matching `audio`.\n- **Anchor Caching**: Targets are parsed once and cached in `_anchors_cache` to keep multi-thousand link audits under 2 seconds.\n\n### 3.4 Data URIs & Media Exclusions\n- Inline image data (`![img](data:image/png;base64,...)`) is excluded via `re.compile(r\"^data:\")` to prevent massive base64 string dumps in error logs.\n- Documentation template placeholders (`URL`, `TODO`) are whitelisted via `LINK_CHECKER_EXCLUDED_TARGETS` in `tools/config.py`.\n\n### 3.5 External HTTP/HTTPS Links (`--all`)\n- Uses `concurrent.futures.ThreadPoolExecutor(max_workers=16)` for parallel HTTP verification.\n- Dispatches HTTP `HEAD` with standard browser `User-Agent`.\n- Automatically retries with HTTP `GET` if the target server rejects `HEAD` with `405 Method Not Allowed` or `403 Forbidden`.\n- Bypasses ignored domains (`localhost`, `127.0.0.1`, Google API endpoints requiring API keys).\n\n---\n\n## 4. GitHub Actions CI Integration\n\nThe workflow `.github/workflows/link_checker.yml` operates in three modes:\n\n1. **Pull Request Mode (`pull_request`)**:\n   - Computes changed files via `git merge-base HEAD ${{ github.event.pull_request.base.sha }}`.\n   - Audits only modified `.ipynb` and `.md` files in `--internal-only` mode.\n   - Completes in `<2` seconds, blocking regressions with zero flaky external network failures.\n2. **Weekly Scheduled Health Check (`schedule: cron '0 8 * * 1'`)**:\n   - Runs on Mondays at 08:00 UTC.\n   - Audits all internal paths AND performs concurrent external HTTP validation across all URLs.\n3. **Manual Dispatch (`workflow_dispatch`)**:\n   - Enables maintainers to run full audits on demand with an optional `check_external` boolean flag.\n","isInternal":false,"tokens":1224,"sizeBytes":5032},{"name":"Design.md","path":"tools/nb_tester/Design.md","rawUrl":"https://raw.githubusercontent.com/google-gemini/cookbook/HEAD/tools/nb_tester/Design.md","title":"Nb_tester Skill","category":"anthropic-skill","format":"markdown","content":"# 📐 Design Document: Notebook Automated Testing, Security & Regression Suite\n\n## 1. Context & Objectives\n\nThe **Gemini API Cookbook** is a central public repository of Python/Jupyter tutorials. Maintaining quality across rapid model releases and SDK iterations introduces two fundamental challenges:\n1. **Security in Open-Source PRs**: Untrusted pull requests from public contributors could execute arbitrary code (RCE) or exfiltrate repo secrets/tokens (`GEMINI_API_KEY`).\n2. **Non-Deterministic Semantic Regressions**: Code might run without raising an exception (exit code 0), but the model's output could regress into low-quality answers, hallucinations, or broken formats.\n3. **Dynamic & Evolving Data**: Grounded search queries (e.g. sports scores, weather) will naturally change over time and require factual verification rather than static string matching.\n\n---\n\n## 2. Threat Model & Multi-Layer Safety Defense\n\n```mermaid\nflowchart TD\n    subgraph Gate1 [Gate 1: Static AST &amp; Regex Scanner]\n        A[PR / Target Notebook] --> B[Parse Code Cells to AST]\n        B --> C{Forbidden calls? eval, exec, os.environ dump}\n        C -- Yes --> D[🚨 Hard Block - Critical Finding]\n        C -- No --> Gate2\n    end\n\n    subgraph Gate2 [Gate 2: Semantic AI Security Auditor]\n        Gate2[Gemini AI Security Model] --> E[Analyze code logic &amp; external URLs]\n        E --> F{Risk Score &lt;= 3 and Verdict == SAFE?}\n        F -- No --> G[🚨 Security Block - Human Review Required]\n        F -- Yes --> Gate3\n    end\n\n    subgraph Gate3 [Gate 3: Isolated Execution &amp; Colab Mock]\n        Gate3[Ephemeral Kernel] --> H[Inject in-memory google.colab.userdata]\n        H --> I[Execute cell-by-cell with timeouts]\n        I --> J[Capture Outputs &amp; Tracebacks]\n    end\n\n    subgraph Gate4 [Gate 4: Output Evaluation &amp; Fact-Checking]\n        J --> K[Exact / Fuzzy / Schema Check]\n        J --> L[Gemini Semantic Output Judge]\n        J --> M[Google Search Grounded Verifier]\n    end\n```\n\n### Safety Guarantees:\n- **No Secret Exposure in Untrusted PRs**: Automated PR checks run zero-secret static AST analysis. Live execution requires explicit maintainer gating.\n- **In-Memory Mocking**: The `google.colab` mock is injected only in the kernel memory at runtime. Notebook files on disk are never altered.\n- **Strict Per-Cell Timeouts**: Prevents infinite loops or stalled network requests from blocking CI pipelines.\n- **Cell-Level Retry & Exponential Backoff**: Transient errors (429 rate limits, 503 unavailable, network timeouts) are automatically retried up to 3 times before failing, while non-retryable syntax errors fail immediately.\n\n---\n\n## 3. Evaluation Strategies\n\n| Strategy | Target | Evaluation Mechanism |\n| :--- | :--- | :--- |\n| `exact_or_fuzzy` | Deterministic outputs (token counting, math, static strings). | Normalizes whitespace and verifies exact match or bounded numeric drift (<= 35%). |\n| `schema_validation` | JSON Mode, Structured Outputs, Function Calling. | Validates that output is syntactically valid JSON matching expected structure. |\n| `semantic_llm` | Creative writing, reasoning, explanations, code generation. | Gemini AI Judge evaluates semantic equivalence, scoring as `MATCH`, `SLIGHT_VARIATION`, or `REGRESSION`. |\n| `grounded_factual` | Real-time queries, sports scores, weather, live search. | Gemini fact-checks output against Google Search Grounding to verify freshness and accuracy. |\n| `ignore_output` | Random UUIDs, timestamps, skipped interactive cells. | Marks cell as `SKIPPED` without evaluating output diffs. |\n\n---\n\n## 4. In-Memory Dynamic Model Overriding (`--model <name>`)\n\nTo test entire test suites or individual tutorials against candidate models (e.g. `gemini-3.7-flash`, `gemini-3.1-pro-preview`) without permanently modifying repository notebooks, `nb_tester` integrates an in-memory AST and regex transformer:\n\n```\n                      ┌─────────────────────────────────────┐\n                      │   Original Notebook (.ipynb file)   │\n                      │  (MODEL_ID = \"gemini-4-hydrogen\")   │\n                      └──────────────────┬──────────────────┘\n                                         │ (Deepcopy in memory)\n                                         ▼\n                      ┌─────────────────────────────────────┐\n                      │    ModelOverrideTransformer        │\n                      │  - Rewrites assignments to MODEL_ID │\n                      │  - Rewrites Colab @param dropdowns  │\n                      │  - Generates kernel preamble        │\n                      └──────────────────┬──────────────────┘\n                                         │\n                                         ▼\n                      ┌─────────────────────────────────────┐\n                      │    Ephemeral IPython Kernel         │\n                      │  (MODEL_ID = \"<override_model>\")    │\n                      │  (os.environ[\"MODEL_ID\"] = \"...\")   │\n                      └─────────────────────────────────────┘\n```\n\n### Safety & Integrity Guarantees:\n- **Zero Disk Mutation**: All AST transformations occur exclusively on in-memory `NotebookNode` copies. Original `.ipynb` files on disk are never altered.\n- **Full Assignment Coverage**: Matches single quotes, double quotes, Colab `# @param` forms, type annotations, and chained assignments.\n- **Preamble Injection**: Injects `MODEL_ID` and environment variables before cell 0 to ensure immediate environment readiness.\n\n---\n\n## 5. Observability & Developer Experience\n\n- **Config Centralization**: All models (`SECURITY_AUDITOR_MODEL`, `OUTPUT_JUDGE_MODEL`, `GROUNDED_VERIFIER_MODEL`, `OVERRIDE_MODEL`), timeouts, and thresholds reside in `config.py`.\n- **LLM Observability**: Every single call to Gemini logs the prompt, generation parameters, response, and duration.\n- **Dry-Run Capability**: Every feature can be validated using `--dry-run` without touching network or filesystem state.\n","isInternal":false,"tokens":1336,"sizeBytes":6462},{"name":"default_rules.yaml","path":"tools/nb_tester/rules/default_rules.yaml","rawUrl":"https://raw.githubusercontent.com/google-gemini/cookbook/HEAD/tools/nb_tester/rules/default_rules.yaml","title":"Rules Skill","category":"anthropic-skill","format":"yaml","content":"# Copyright 2026 Google LLC\n# Default Testing & Exception Rules for Gemini API Cookbook Notebooks\n\n# Global defaults across all notebooks unless overridden\nglobal_defaults:\n  cell_timeout_sec: 240\n  notebook_timeout_sec: 1200\n  default_strategy: \"semantic_llm\"\n  cell_max_retries: 3\n  cell_retry_backoff_sec: 2.0\n\n# Specific notebook overrides\nnotebooks:\n  quickstarts/Counting_Tokens.ipynb:\n    cell_timeout_sec: 60\n    cells:\n      - match: \"client.models.count_tokens\"\n        strategy: \"exact_or_fuzzy\"\n        description: \"Token counting outputs are deterministic integers\"\n\n  quickstarts/Grounding.ipynb:\n    cells:\n      - match: \"client.models.generate_content\"\n        strategy: \"grounded_factual\"\n        description: \"Live search grounded responses may evolve over time; double check with Google Search\"\n\n  quickstarts/Search_Grounding.ipynb:\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1200\n    allow_dynamic_exec: true\n    allow_security_demo: true\n    cells:\n      - match: \"client.models.generate_content\"\n        strategy: \"grounded_factual\"\n        description: \"Verify factual correctness of live Google Search results\"\n\n  quickstarts/JSON_mode.ipynb:\n    cells:\n      - match: \"response_mime_type=\\\"application/json\\\"\"\n        strategy: \"schema_validation\"\n        description: \"Validates JSON structure conformance\"\n\n  quickstarts/Interactive_Chat.ipynb:\n    cells:\n      - match: \"input(\"\n        action: \"skip\"\n        reason: \"Interactive user input cell cannot execute in headless CI\"\n\n  quickstarts/Authentication_with_OAuth.ipynb:\n    skip_notebook: true\n    skip_reason: \"Requires interactive browser OAuth login flow\"\n\n  quickstarts/Webhooks.ipynb:\n    skip_notebook: true\n    skip_reason: \"Requires live webhook receiver server endpoint\"\n\n  quickstarts/Get_started_Veo.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1500\n    description: \"Video generation takes longer than text generation\"\n\n  quickstarts/Get_started_Veo_REST.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1500\n    description: \"REST Veo video generation and polling\"\n\n  quickstarts/Batch_mode.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1800\n    description: \"Asynchronous Batch API job polling can take 5-15 minutes\"\n\n  quickstarts/File_API.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1500\n    description: \"Uploads and processes a 45-minute video via File API\"\n\n  quickstarts/Get_started_Lyria.ipynb:\n    long_running: true\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1200\n    description: \"Real-time Lyria music generation streaming\"\n\n  quickstarts/Tuning.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1800\n    description: \"Model tuning job creation and training loop\"\n\n  quickstarts/Get_started_Deep_Research.ipynb:\n    long_running: true\n    cell_timeout_sec: 1800\n    notebook_timeout_sec: 2400\n    description: \"Deep Research queries can take up to 30+ minutes\"\n\n  quickstarts/Get_Started_Nano_Banana.ipynb:\n    cell_timeout_sec: 180\n    notebook_timeout_sec: 1800\n    description: \"Image generation and multi-turn image editing\"\n\n  quickstarts/Get_started_thinking.ipynb:\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1800\n    description: \"Extended thinking generation chains can take up to 10 minutes per cell\"\n\n  quickstarts/Get_started_thinking_REST.ipynb:\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1200\n    description: \"Thinking REST endpoint multi-turn analysis\"\n\n  quickstarts/Get_started_Omni.ipynb:\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1200\n    description: \"Omni multimodal model processing\"\n\n  quickstarts/Video_understanding.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1500\n    description: \"Video upload, processing, and multi-turn frame analysis\"\n\n  quickstarts/Inference_tiers.ipynb:\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1200\n    description: \"Multi-tier model benchmarking and latency comparison\"\n\n  quickstarts/Get_started.ipynb:\n    cell_timeout_sec: 300\n    notebook_timeout_sec: 1200\n    description: \"Full tour of multimodal features across large files\"\n\n  examples/Virtual_Try_On.ipynb:\n    skip_notebook: true\n    skip_reason: \"Requires interactive Colab Vertex AI auth (auth.authenticate_user)\"\n\n  examples/Google_IO2025_Live_Coding.ipynb:\n    skip_notebook: true\n    skip_reason: \"Historical event notebook kept frozen with original Google I/O 2025 models\"\n\n  examples/Book_illustration.ipynb:\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1800\n    description: \"Multimodal audio, TTS, image generation, and MoviePy mix\"\n\n  examples/gemini_google_adk_model_guardrails.ipynb:\n    allow_security_demo: true\n    description: \"Demonstrates model guardrails against prompt injection and backdoors\"\n\n  examples/LiveAPI_plotting_and_mapping.ipynb:\n    allow_dynamic_exec: true\n    allow_security_demo: true\n    description: \"Demonstrates live plotting and mapping using code execution tools\"\n\n  examples/prompting/Basic_Code_Generation.ipynb:\n    allow_dynamic_exec: true\n    allow_security_demo: true\n    description: \"Demonstrates generating and executing Python code via exec()\"\n","isInternal":false,"tokens":1312,"sizeBytes":5297},{"name":"README.md","path":"tools/nb_tester/README.md","rawUrl":"https://raw.githubusercontent.com/google-gemini/cookbook/HEAD/tools/nb_tester/README.md","title":"nb_tester Documentation","category":"plugin-manifest","format":"markdown","content":"# 🧪 Gemini API Cookbook Notebook Testing & Regression Suite\n\nAn automated, security-gated test runner and semantic regression evaluator designed specifically for the Jupyter/Colab notebooks in the [Gemini API Cookbook](https://github.com/google-gemini/cookbook).\n\n---\n\n## 🌟 Key Features\n\n1. **🔒 Multi-Layer Security Architecture (Preventing RCE & Key Theft)**:\n   - **Level 1 (Static AST Scanner)**: Fast, zero-secret AST checks for forbidden system calls, reverse shells, and raw environment dumps.\n   - **Level 2 (Gemini AI Security Auditor)**: Semantic code review with structured JSON output before any code execution to detect subtle backdoors, malicious `%pip` dependencies, or data exfiltration.\n   - **Zero-Disk-Tampering Colab Mock**: Injects a virtual `google.colab.userdata` module into the kernel namespace in memory, keeping notebooks clean and keys secure.\n2. **⚖️ Semantic Output Regression Judging**:\n   - Compares newly generated outputs with the saved reference outputs in the repository.\n   - Uses Gemini AI Judge to separate normal non-deterministic phrasing differences (`SLIGHT_VARIATION`) from true broken answers or hallucinations (`REGRESSION`).\n3. **🌐 Google Search Grounding Verification**:\n   - For real-time and time-evolving queries (e.g. sports scores, weather, current events), uses Gemini with the Google Search tool to double-check that new answers are factually true today.\n4. **📋 Declarative Rules & Exception Registry (`rules/default_rules.yaml`)**:\n   - Easily configure cell-level actions (e.g. skipping interactive `input()` cells) and per-notebook timeouts.\n5. **🎯 Family-Aware Dynamic Model Identifier Override (`--model <name>`)**:\n   - Test the entire cookbook (or specific notebooks) against candidate or pre-release models (e.g. `gemini-4-hydrogen`, `gemini-3.8-flash`, `gemini-3.1-pro-preview`) by dynamically overriding `MODEL_ID` in memory across compatible cells without touching disk.\n   - Automatically preserves specialized non-text models (`-live`, `-tts`, `-image`, `embedding`, `veo`, `lyria`, `transcribe`) unless the override model itself belongs to that same model family.\n6. **📊 CI & Pull Request Integration**:\n   - Generates persistent JSON reports under `reports/` and auto-appends formatted Markdown tables to `$GITHUB_STEP_SUMMARY`.\n   - Returns clean exit codes (`0` on pass, `1` on failure) for automated gating.\n7. **🔍 Dry-Run Mode**:\n   - Test rule configurations, AST checks, model overrides, and syntax parsing without altering files, spinning up kernels, or consuming API tokens.\n8. **🔁 Automatic Cell-Level Retry & Exponential Backoff**:\n   - Automatically retries failed cells (up to 3 times by default with exponential backoff) on transient API errors (429, 503, timeouts) before failing, preventing flaky CI runs while skipping non-retryable syntax errors. Configurable via `--max-retries` CLI flag or `rules/default_rules.yaml`.\n\n---\n\n## 🛠️ System Prerequisites (Local Execution)\n\nIn Google Colab, `ffmpeg`, `jq`, and `curl` are pre-installed in the default runtime container (and `poppler-utils` is installed via `!apt-get install -y -q poppler-utils` inside `quickstarts/PDF_Files.ipynb`).\n\nWhen running `tools/nb_tester` locally on a Linux/macOS workstation or headless CI runner (where notebooks do not execute as `root`), install the following system packages first so audio, video, PDF (`pdf2image` / `pdftoppm`), and REST (`curl` + `jq`) notebooks execute cleanly:\n\n```bash\n# Ubuntu / Debian / gLinux\nsudo apt-get update && sudo apt-get install -y ffmpeg poppler-utils jq curl\n```\n\n---\n\n## 🚀 Quickstart & Usage\n\n### 1. Dry-Run Mode (Safe simulation)\n```bash\npython3 -m tools.nb_tester.cli --notebook quickstarts/Counting_Tokens.ipynb --dry-run\n```\n\n### 2. Security Audit Only (No code execution)\n```bash\npython3 -m tools.nb_tester.cli --notebook quickstarts/Prompting.ipynb --security-only\n```\n\n### 3. Test a Single Notebook with Live Execution & AI Judge\n```bash\nexport GEMINI_API_KEY=\"your-api-key\"\npython3 -m tools.nb_tester.cli --notebook quickstarts/Counting_Tokens.ipynb\n```\n\n### 4. Test Only Changed Notebooks in a PR / Git Branch\n```bash\npython3 -m tools.nb_tester.cli --changed\n```\n\n### 5. Test Notebooks with Dynamic Model Override\n```bash\n# Run a specific quickstart against a candidate/preview model\npython3 -m tools.nb_tester.cli --notebook quickstarts/Get_started_thinking.ipynb --model gemini-3.1-pro-preview\n\n# Run all quickstarts with model override in parallel\npython3 -m tools.nb_tester.cli --all --model gemini-3.7-flash --workers 4\n```\n\n### 6. Run Full Suite in Parallel\n```bash\npython3 -m tools.nb_tester.cli --all --workers 4\n```\n\n---\n\n## ⚙️ Configuration & Exception Rules\n\nRules are declared in `tools/nb_tester/rules/default_rules.yaml`.\n\n```yaml\nglobal_defaults:\n  cell_timeout_sec: 90\n  notebook_timeout_sec: 600\n  default_strategy: \"semantic_llm\"\n\nnotebooks:\n  quickstarts/Grounding.ipynb:\n    cells:\n      - match: \"client.models.generate_content\"\n        strategy: \"grounded_factual\"\n        description: \"Verify dynamic search output using Google Search\"\n\n  quickstarts/Interactive_Chat.ipynb:\n    cells:\n      - match: \"input(\"\n        action: \"skip\"\n        reason: \"Interactive user input not supported in headless CI\"\n```\n\n---\n\n## 🏗️ Architecture & Modules\n\n```\ntools/nb_tester/\n├── config.py             # Centralized models, timeouts, and GEMINI_API_KEY resolution\n├── logger.py             # Structured logging with complete LLM prompt/response tracking\n├── security_scanner.py   # Level 1: Deterministic AST & regex scanner\n├── ai_security_auditor.py# Level 2: Gemini AI Semantic Security Auditor\n├── rules.py              # Declarative rules engine and matcher\n├── model_override.py     # In-memory MODEL_ID override transformer & preamble injector\n├── executor.py           # nbclient kernel executor with in-memory Colab mock\n├── comparator.py         # Output snapshot extractor and strategy router\n├── llm_judge.py          # Level 3: Semantic output regression judge\n├── grounded_verifier.py  # Real-time fact-checking via Google Search Grounding\n├── reporter.py           # Multi-format report builder (JSON, Step Summary, Terminal)\n├── cli.py                # Command-line interface entry point\n└── rules/\n    └── default_rules.yaml# Default rule definitions and exceptions\n```\n","isInternal":false,"tokens":1563,"sizeBytes":6442},{"name":"README.md","path":"tools/README.md","rawUrl":"https://raw.githubusercontent.com/google-gemini/cookbook/HEAD/tools/README.md","title":"tools Documentation","category":"plugin-manifest","format":"markdown","content":"# Gemini API Cookbook Quality Assurance & Linting Tools\n\nThis directory contains standalone tools for formatting, linting, and maintaining Jupyter/Colab notebooks in the [Gemini API Cookbook](https://github.com/google-gemini/cookbook).\n\nThese tools are natively hosted in this repository to provide fast, zero-dependency validation tailored specifically to the Gemini SDK and cookbook style guidelines.\n\n---\n\n## Tools Overview\n\n| Tool | Script | Description |\n| :--- | :--- | :--- |\n| **`nblint`** | `tools/nblint_cli.py` | Lints notebooks for licensing, structure, style, SDK best practices, and model selectors. |\n| **`nbfmt`** | `tools/nbfmt_cli.py` | Automatically formats notebook JSON, standardizes metadata, strips empty cells, and aligns code formatting. |\n| **`readme_links`** | `tools/check_readme_links.py` | Validates that new/modified notebooks are linked in section Table of Contents READMEs. |\n| **`check_all_links`** | `tools/check_all_links.py` | Audits internal paths, anchors, blob URLs, and external links across `.md` and `.ipynb` files. |\n| **`config`** | `tools/config.py` | Central configuration file containing model hierarchies, wordlists, exclusions, and URL rules. |\n\n---\n\n## 1. Quickstart Usage\n\n### Linting Notebooks\n```bash\n# Lint a specific notebook\npython tools/nblint_cli.py quickstarts/Get_started.ipynb\n\n# Lint multiple notebooks or directories\npython tools/nblint_cli.py quickstarts/**/*.ipynb examples/**/*.ipynb\n\n# Perform a dry-run check\npython tools/nblint_cli.py --dry-run quickstarts/Get_started.ipynb\n\n# Specify custom branch or repository\npython tools/nblint_cli.py --repo=google-gemini/cookbook --branch=main path/to/notebook.ipynb\n```\n\n### Formatting Notebooks\n```bash\n# Format a specific notebook (modifies file in place)\npython tools/nbfmt_cli.py quickstarts/Get_started.ipynb\n\n# Test if notebooks are properly formatted (without modifying, returns non-zero on unformatted)\npython tools/nbfmt_cli.py --test quickstarts/**/*.ipynb\n\n# Format all notebooks in the repo\npython tools/nbfmt_cli.py quickstarts/**/*.ipynb examples/**/*.ipynb\n```\n\n### Checking Table of Contents README Links\n```bash\n# Check if a specific notebook is linked in its folder/section README.md\npython tools/check_readme_links.py quickstarts/Get_started.ipynb\n\n# Audit all notebooks in the repo\npython tools/check_readme_links.py --all\n```\n\n### Verifying Internal and External Links\n```bash\n# Validate internal links and anchors on specific files (fast CI check)\npython tools/check_all_links.py quickstarts/Get_started.ipynb README.md\n\n# Validate all git-modified files against upstream/main\npython tools/check_all_links.py --changed\n\n# Full repository audit of all internal relative links and anchor slugs\npython tools/check_all_links.py\n\n# Full repository audit including live external HTTP/HTTPS health checks\npython tools/check_all_links.py --all\n```\n\n---\n\n## 2. Lint Rules Reference\n\n### Python Syntax Rules (`tools/nblint/rules/syntax.py`)\n- **`syntax::code_cell`**: Parses code cells, including `%%time` bodies, with `ast.parse` after neutralizing IPython magics and shell escapes. Other `%%` cell magics are skipped. Reports the cell index and original line of any `SyntaxError`.\n\n### Structure Rules (`tools/nblint/rules/structure.py`)\n- **`structure::copyright`**: Verifies that cell 0 contains a valid Google / Gemini copyright statement (`##### Copyright 2026 Google LLC.`).\n- **`structure::license`**: Verifies that the notebook contains a collapsed Apache 2.0 license code cell with `# @title Licensed under the Apache License`.\n- **`structure::colab_button`**: Checks for the \"Open in Colab\" badge and verifies that its destination URL matches `https://colab.research.google.com/github/<repo>/blob/<branch>/<path>`. Automatically adjusts for redirect stubs.\n- **`structure::next_steps`**: Emits a warning if a closing section is missing. Accepted headings: \"Next steps\", \"What's next\", \"Learn more\" / \"Learning more\", \"Further reading\" / \"Further resources\" or \"Conclusion\".\n\n### Style & Language Rules (`tools/nblint/rules/style.py`)\n- **`style::inclusive_language`**: Flags discouraged terminology (`blacklist`, `whitelist`, `master`, `slave`) and suggests modern alternatives. **Note**: The word `\"native\"` is deliberately allowed because terms like *\"native audio\"*, *\"native TTS\"*, and *\"native multimodal\"* are standard Gemini API features.\n- **`style::second_person`**: Ensures narrative explanations in markdown use second person (*you*) rather than first person (*we*). Prompt strings, quoted examples, and code comments are ignored.\n- **`style::line_length`**: Warns when code lines exceed 100 characters (ignoring URLs, form annotations, and long multiline strings).\n\n### Gemini SDK & API Best Practices (`tools/nblint/rules/gemini.py`)\n- **`gemini::pip_magic`**: Enforces `%pip install` instead of `!pip install` for reliable kernel-level package installation.\n- **`gemini::sdk_package`**: Enforces the official `from google import genai` (`google-genai`) SDK, flagging deprecated `google.generativeai`.\n- **`gemini::api_key_secret`**: Checks that notebooks retrieve API keys from `userdata.get('GEMINI_API_KEY')` rather than the legacy `GOOGLE_API_KEY` secret.\n- **`gemini::hardcoded_api_key`**: Scans all cells for accidental plaintext Google/Gemini API keys (legacy `AIza...` and new `AQ.Ab8...` formats) to prevent credential leakage.\n\n### Model Selector Validation (`tools/nblint/rules/model_selector.py`)\n- **`gemini::model_selector`**:\n  - Verifies that model selectors use the canonical Colab form pattern:\n    ```python\n    MODEL_ID = \"gemini-3.7-flash\" # @param [\"gemini-3.1-pro-preview\", \"gemini-3.7-flash\", \"gemini-3.5-flash-lite\"] {\"allow-input\":true, isTemplate: true}\n    ```\n  - Verifies that the default assigned model exists in the option list.\n  - Verifies that models in the list are sorted in logical order from most capable to least capable: **current generation (Pro $\\rightarrow$ Flash $\\rightarrow$ Flash-Lite)**, followed by **previous generation (e.g. Gemini 3.x)**.\n\n---\n\n## 3. Configuration & Exclusions\n\nAll configurable settings are consolidated in `tools/config.py`:\n- **`EXCLUDED_NOTEBOOKS`**: List of files skipped during automated lint runs (e.g. `quickstarts/Template.ipynb`).\n- **`REDIRECT_KEYWORDS`**: Keywords used to automatically detect redirection stubs (e.g. `gemini-robotics-er.ipynb`) and apply lenient rules.\n- **`get_model_sort_key(model_name)`**: Ranking algorithm for model selector ordering.\n- **`INCLUSIVE_LANGUAGE_WORDLIST`**: Mapping of discouraged terms to replacements.\n","isInternal":false,"tokens":1585,"sizeBytes":6571}],"systemPromptSnippet":"<yakaai_skills repo=\"google-gemini/cookbook\">\n<!-- File: tools/Design.md (Tokens: ~906 | Category: project-spec) -->\n# Gemini API Cookbook Quality Assurance Tools: Architecture & Design\n\n## 1. Background & Motivation\n\nPreviously, the Gemini API Cookbook's CI and developer workflows relied on the external package `tensorflow-docs` (`github.com/tensorflow/docs`) for notebook formatting (`nbfmt`) and linting (`nblint`).\n\nThis legacy setup created several critical operational problems:\n1. **External Dependency**: CI had to install `git+https://github.com/tensorflow/docs` on every workflow run. Any changes or fixes required modifying a separate repository.\n2. **False Positives on \"native\"**: `tensorflow/docs` included `\"native\": \"built-in\"` in its inclusive language wordlist. In the Gemini ecosystem, terms like *\"native audio\"*, *\"native TTS\"*, *\"native multimodal output\"*, and model IDs like `gemini-2.5-flash-native-audio-preview` are official terminology, causing CI to fail on valid PRs.\n3. **Overly Strict First-Person Flags**: The legacy linter flagged words like `\"we\"` inside code comments and string parameters (e.g. `text_prompt = \"we can see the stage...\"`).\n4. **Irrelevant Legacy Rules**: Checks for TensorFlow 1.x `r1/` directories and `tfhub.dev` buttons had to be manually excluded in CI commands.\n5. **Lack of Gemini-Specific Checks**: Common review issues—such as using `!pip` instead of `%pip`, legacy `google.generativeai` imports, `GOOGLE_API_KEY` vs `GEMINI_API_KEY`, model selector ordering, and hardcoded API keys—had to be caught manually by maintainers.\n\n## 2. Design Principles & Goals\n\n1. **Zero External Tool Dependencies**: Implemented using standard Python libraries (`json`, `pathlib`, `re`, `logging`, `argparse`, `dataclasses`).\n2. **Centralized Configuration**: All configurable parameters, model order ranks, excluded files, and wordlists reside in `tools/config.py`.\n3. **Modular Rule Architecture**: Separate rule modules for structure, style, SDK best practices, and model selector formatting.\n4. **First-Class Support for Special Notebooks**:\n   - **Template Notebook**: Explicitly excluded from full strictness tests.\n   - **Redirect Stubs**: Auto-detected via cell count and content keywords, skipping full content and Colab button mismatch failures.\n5. **Comprehensive Logging & Dry-Run**: Detailed INFO and DEBUG logs, and full `--dry-run` and `--test` support for safe local and CI testing.\n\n## 3. Directory Layout\n\n```\ntools/\n├── __init__.py\n├── config.py                 # Centralized configuration & model hierarchies\n├── nblint/                   # Linter core & rule implementations\n│   ├── __init__.py\n│   ├── linter.py             # Linter execution engine & result aggregation\n│   └── rules/\n│       ├── __init__.py\n│       ├── structure.py      # Copyright, License, Colab button, Next steps\n│       ├── style.py          # Inclusive language (no native), Second person\n│       ├── gemini.py         # %pip vs !pip, google-genai SDK, GEMINI_API_KEY, no leaks\n│       └── model_selector.py # @param Colab form & model ordering validation\n├── nbfmt/                    # Formatter core\n│   ├── __init__.py\n│   └── formatter.py          # JSON normalization, metadata & cell cleaning\n├── nblint_cli.py             # CLI entrypoint for linting\n├── nbfmt_cli.py             # CLI entrypoint for formatting\n├── README.md                 # User guide and CLI reference\n└── Design.md                 # Architecture and design rationale (this document)\n```\n\n## 4. Model Hierarchy & Ordering Logic\n\nIn `tools/config.py`, the model selector rule sorts models using `get_model_sort_key()`:\n- **Capability Tiers**: Models are ordered from most capable to least capable: Pro $\\rightarrow$ Flash $\\rightarrow$ Flash-Lite $\\rightarrow$ Domain-specific (Live/Veo/Imagen/Lyria).\n- **Generations**: Current generation models (e.g. Gemini 4.x) precede previous generations (e.g. Gemini 3.x).\n\n<!-- File: tools/link_checker/Design.md (Tokens: ~1224 | Category: anthropic-skill) -->\n# Architecture & Design: Cookbook Link Checker (`tools/check_all_links.py`)\n\n## 1. Overview & Objectives\n\nThe **Cookbook Link Checker** is an automated quality gate designed to prevent broken, dead, or misdirected links from entering the `google-gemini/cookbook` repository. It audits both Markdown documentation (`.md`) and Jupyter Notebooks (`.ipynb`), providing sub-second validation for Pull Requests and comprehensive health checks for scheduled maintenance.\n\n### Primary Goals:\n1. **Zero Broken Links at PR Merge**: Catch renamed notebooks, deleted files, invalid relative paths, and broken anchor links before merging.\n2. **Sub-Second CI Runtime**: Ensure that PR checks on modified files execute in `<1-2s` without depending on external network calls.\n3. **Deep Anchor Validation**: Validate `#anchor-name` targets both in-page and cross-file, matching GitHub's Markdown slugification rules and HTML `<a name=\"...\">` tags.\n4. **Seamless Integration**: Native Python standard library implementation with zero external dependencies (no `requests`, `beautifulsoup4`, or `curl` required).\n\n---\n\n## 2. Architecture & Scanning Pipeline\n\n```mermaid\nflowchart TD\n    A[\"CLI / CI Trigger\"] --> B[\"Target File Resolution<br/>(explicit paths, --changed, or full repo)\"]\n    B --> C[\"Link Extraction<br/>(Markdown [text](url) & HTML <a href=...>)\"]\n    C --> D{\"Scheme & Pattern Filter\"}\n    D -->|\"data:, mailto:, tel:, javascript:\"| E[\"Ignored / Skipped\"]\n    D -->|\"Blob URL: github.com/.../blob/main/...\"| F[\"Local Disk Path Resolver\"]\n    D -->|\"Internal Relative Path<br/>(../path.ipynb#heading)\"| G[\"Path Traversal & Anchor Checker\"]\n    D -->|\"External HTTP/HTTPS<br/>(when --all enabled)\"| H[\"Concurrent Worker Pool<br/>(ThreadPoolExecutor)\"]\n    \n    F --> I[\"Anchor & File Validator\"]\n    G --> I\n    I --> J[\"In-Memory Anchor Cache<br/>(_anchors_cache)\"]\n    \n    H --> K{\"HEAD Status\"}\n    K -->|\"200-399\"| L[\"Valid\"]\n    K -->|\"403 / 405\"| M[\"Fallback to GET\"]\n    K -->|\"404 / 500 / Timeout\"| N[\"Report Broken\"]\n    \n    I --> O[\"Aggregation & Exit Code\"]\n    N --> O\n    L --> O\n```\n\n---\n\n## 3. Link Categories & Resolution Rules\n\n### 3.1 Internal Relative Links (`./...`, `../...`)\n- Resolves paths relative to the parent directory of the source file.\n- Guards against path traversal vulnerabilities by enforcing `target_path.relative_to(repo_root)`.\n- Verifies physical file existence on disk.\n\n### 3.2 GitHub Repository Blob URLs (`https://github.com/google-gemini/cookbook/blob/main/...`)\n- Contributors often write absolute GitHub blob URLs pointing to other cookbook files.\n- The tool intercepts links starting with `https://github.com/google-gemini/cookbook/blob/main/` and maps them directly to the local clone working tree.\n- Catches broken links introduced during renames even if the external branch has not yet been pushed or merged.\n\n### 3.3 Anchor Fragment Verification (`#...`)\n- **Colab UI Fragments**: `#scrollTo=...` is recognized as a Google Colab cell identifier and validated against cell IDs or gracefully allowed.\n- **In-Page Anchors**: `#heading-title` in `README.md` validates that `heading-title` exists as a slugified heading or HTML `<a name=\"...\">` in `README.md`.\n- **Cross-File Anchors**: `quickstarts/Get_started.ipynb#audio` validates that `quickstarts/Get_started.ipynb` exists and contains an anchor or heading slug matching `audio`.\n- **Anchor Caching**: Targets are parsed once and cached in `_anchors_cache` to keep multi-thousand link audits under 2 seconds.\n\n### 3.4 Data URIs & Media Exclusions\n- Inline image data (`![img](data:image/png;base64,...)`) is excluded via `re.compile(r\"^data:\")` to prevent massive base64 string dumps in error logs.\n- Documentation template placeholders (`URL`, `TODO`) are whitelisted via `LINK_CHECKER_EXCLUDED_TARGETS` in `tools/config.py`.\n\n### 3.5 External HTTP/HTTPS Links (`--all`)\n- Uses `concurrent.futures.ThreadPoolExecutor(max_workers=16)` for parallel HTTP verification.\n- Dispatches HTTP `HEAD` with standard browser `User-Agent`.\n- Automatically retries with HTTP `GET` if the target server rejects `HEAD` with `405 Method Not Allowed` or `403 Forbidden`.\n- Bypasses ignored domains (`localhost`, `127.0.0.1`, Google API endpoints requiring API keys).\n\n---\n\n## 4. GitHub Actions CI Integration\n\nThe workflow `.github/workflows/link_checker.yml` operates in three modes:\n\n1. **Pull Request Mode (`pull_request`)**:\n   - Computes changed files via `git merge-base HEAD ${{ github.event.pull_request.base.sha }}`.\n   - Audits only modified `.ipynb` and `.md` files in `--internal-only` mode.\n   - Completes in `<2` seconds, blocking regressions with zero flaky external network failures.\n2. **Weekly Scheduled Health Check (`schedule: cron '0 8 * * 1'`)**:\n   - Runs on Mondays at 08:00 UTC.\n   - Audits all internal paths AND performs concurrent external HTTP validation across all URLs.\n3. **Manual Dispatch (`workflow_dispatch`)**:\n   - Enables maintainers to run full audits on demand with an optional `check_external` boolean flag.\n\n<!-- File: tools/nb_tester/Design.md (Tokens: ~1336 | Category: anthropic-skill) -->\n# 📐 Design Document: Notebook Automated Testing, Security & Regression Suite\n\n## 1. Context & Objectives\n\nThe **Gemini API Cookbook** is a central public repository of Python/Jupyter tutorials. Maintaining quality across rapid model releases and SDK iterations introduces two fundamental challenges:\n1. **Security in Open-Source PRs**: Untrusted pull requests from public contributors could execute arbitrary code (RCE) or exfiltrate repo secrets/tokens (`GEMINI_API_KEY`).\n2. **Non-Deterministic Semantic Regressions**: Code might run without raising an exception (exit code 0), but the model's output could regress into low-quality answers, hallucinations, or broken formats.\n3. **Dynamic & Evolving Data**: Grounded search queries (e.g. sports scores, weather) will naturally change over time and require factual verification rather than static string matching.\n\n---\n\n## 2. Threat Model & Multi-Layer Safety Defense\n\n```mermaid\nflowchart TD\n    subgraph Gate1 [Gate 1: Static AST &amp; Regex Scanner]\n        A[PR / Target Notebook] --> B[Parse Code Cells to AST]\n        B --> C{Forbidden calls? eval, exec, os.environ dump}\n        C -- Yes --> D[🚨 Hard Block - Critical Finding]\n        C -- No --> Gate2\n    end\n\n    subgraph Gate2 [Gate 2: Semantic AI Security Auditor]\n        Gate2[Gemini AI Security Model] --> E[Analyze code logic &amp; external URLs]\n        E --> F{Risk Score &lt;= 3 and Verdict == SAFE?}\n        F -- No --> G[🚨 Security Block - Human Review Required]\n        F -- Yes --> Gate3\n    end\n\n    subgraph Gate3 [Gate 3: Isolated Execution &amp; Colab Mock]\n        Gate3[Ephemeral Kernel] --> H[Inject in-memory google.colab.userdata]\n        H --> I[Execute cell-by-cell with timeouts]\n        I --> J[Capture Outputs &amp; Tracebacks]\n    end\n\n    subgraph Gate4 [Gate 4: Output Evaluation &amp; Fact-Checking]\n        J --> K[Exact / Fuzzy / Schema Check]\n        J --> L[Gemini Semantic Output Judge]\n        J --> M[Google Search Grounded Verifier]\n    end\n```\n\n### Safety Guarantees:\n- **No Secret Exposure in Untrusted PRs**: Automated PR checks run zero-secret static AST analysis. Live execution requires explicit maintainer gating.\n- **In-Memory Mocking**: The `google.colab` mock is injected only in the kernel memory at runtime. Notebook files on disk are never altered.\n- **Strict Per-Cell Timeouts**: Prevents infinite loops or stalled network requests from blocking CI pipelines.\n- **Cell-Level Retry & Exponential Backoff**: Transient errors (429 rate limits, 503 unavailable, network timeouts) are automatically retried up to 3 times before failing, while non-retryable syntax errors fail immediately.\n\n---\n\n## 3. Evaluation Strategies\n\n| Strategy | Target | Evaluation Mechanism |\n| :--- | :--- | :--- |\n| `exact_or_fuzzy` | Deterministic outputs (token counting, math, static strings). | Normalizes whitespace and verifies exact match or bounded numeric drift (<= 35%). |\n| `schema_validation` | JSON Mode, Structured Outputs, Function Calling. | Validates that output is syntactically valid JSON matching expected structure. |\n| `semantic_llm` | Creative writing, reasoning, explanations, code generation. | Gemini AI Judge evaluates semantic equivalence, scoring as `MATCH`, `SLIGHT_VARIATION`, or `REGRESSION`. |\n| `grounded_factual` | Real-time queries, sports scores, weather, live search. | Gemini fact-checks output against Google Search Grounding to verify freshness and accuracy. |\n| `ignore_output` | Random UUIDs, timestamps, skipped interactive cells. | Marks cell as `SKIPPED` without evaluating output diffs. |\n\n---\n\n## 4. In-Memory Dynamic Model Overriding (`--model <name>`)\n\nTo test entire test suites or individual tutorials against candidate models (e.g. `gemini-3.7-flash`, `gemini-3.1-pro-preview`) without permanently modifying repository notebooks, `nb_tester` integrates an in-memory AST and regex transformer:\n\n```\n                      ┌─────────────────────────────────────┐\n                      │   Original Notebook (.ipynb file)   │\n                      │  (MODEL_ID = \"gemini-4-hydrogen\")   │\n                      └──────────────────┬──────────────────┘\n                                         │ (Deepcopy in memory)\n                                         ▼\n                      ┌─────────────────────────────────────┐\n                      │    ModelOverrideTransformer        │\n                      │  - Rewrites assignments to MODEL_ID │\n                      │  - Rewrites Colab @param dropdowns  │\n                      │  - Generates kernel preamble        │\n                      └──────────────────┬──────────────────┘\n                                         │\n                                         ▼\n                      ┌─────────────────────────────────────┐\n                      │    Ephemeral IPython Kernel         │\n                      │  (MODEL_ID = \"<override_model>\")    │\n                      │  (os.environ[\"MODEL_ID\"] = \"...\")   │\n                      └─────────────────────────────────────┘\n```\n\n### Safety & Integrity Guarantees:\n- **Zero Disk Mutation**: All AST transformations occur exclusively on in-memory `NotebookNode` copies. Original `.ipynb` files on disk are never altered.\n- **Full Assignment Coverage**: Matches single quotes, double quotes, Colab `# @param` forms, type annotations, and chained assignments.\n- **Preamble Injection**: Injects `MODEL_ID` and environment variables before cell 0 to ensure immediate environment readiness.\n\n---\n\n## 5. Observability & Developer Experience\n\n- **Config Centralization**: All models (`SECURITY_AUDITOR_MODEL`, `OUTPUT_JUDGE_MODEL`, `GROUNDED_VERIFIER_MODEL`, `OVERRIDE_MODEL`), timeouts, and thresholds reside in `config.py`.\n- **LLM Observability**: Every single call to Gemini logs the prompt, generation parameters, response, and duration.\n- **Dry-Run Capability**: Every feature can be validated using `--dry-run` without touching network or filesystem state.\n\n<!-- File: tools/nb_tester/rules/default_rules.yaml (Tokens: ~1312 | Category: anthropic-skill) -->\n# Copyright 2026 Google LLC\n# Default Testing & Exception Rules for Gemini API Cookbook Notebooks\n\n# Global defaults across all notebooks unless overridden\nglobal_defaults:\n  cell_timeout_sec: 240\n  notebook_timeout_sec: 1200\n  default_strategy: \"semantic_llm\"\n  cell_max_retries: 3\n  cell_retry_backoff_sec: 2.0\n\n# Specific notebook overrides\nnotebooks:\n  quickstarts/Counting_Tokens.ipynb:\n    cell_timeout_sec: 60\n    cells:\n      - match: \"client.models.count_tokens\"\n        strategy: \"exact_or_fuzzy\"\n        description: \"Token counting outputs are deterministic integers\"\n\n  quickstarts/Grounding.ipynb:\n    cells:\n      - match: \"client.models.generate_content\"\n        strategy: \"grounded_factual\"\n        description: \"Live search grounded responses may evolve over time; double check with Google Search\"\n\n  quickstarts/Search_Grounding.ipynb:\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1200\n    allow_dynamic_exec: true\n    allow_security_demo: true\n    cells:\n      - match: \"client.models.generate_content\"\n        strategy: \"grounded_factual\"\n        description: \"Verify factual correctness of live Google Search results\"\n\n  quickstarts/JSON_mode.ipynb:\n    cells:\n      - match: \"response_mime_type=\\\"application/json\\\"\"\n        strategy: \"schema_validation\"\n        description: \"Validates JSON structure conformance\"\n\n  quickstarts/Interactive_Chat.ipynb:\n    cells:\n      - match: \"input(\"\n        action: \"skip\"\n        reason: \"Interactive user input cell cannot execute in headless CI\"\n\n  quickstarts/Authentication_with_OAuth.ipynb:\n    skip_notebook: true\n    skip_reason: \"Requires interactive browser OAuth login flow\"\n\n  quickstarts/Webhooks.ipynb:\n    skip_notebook: true\n    skip_reason: \"Requires live webhook receiver server endpoint\"\n\n  quickstarts/Get_started_Veo.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1500\n    description: \"Video generation takes longer than text generation\"\n\n  quickstarts/Get_started_Veo_REST.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1500\n    description: \"REST Veo video generation and polling\"\n\n  quickstarts/Batch_mode.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1800\n    description: \"Asynchronous Batch API job polling can take 5-15 minutes\"\n\n  quickstarts/File_API.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1500\n    description: \"Uploads and processes a 45-minute video via File API\"\n\n  quickstarts/Get_started_Lyria.ipynb:\n    long_running: true\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1200\n    description: \"Real-time Lyria music generation streaming\"\n\n  quickstarts/Tuning.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1800\n    description: \"Model tuning job creation and training loop\"\n\n  quickstarts/Get_started_Deep_Research.ipynb:\n    long_running: true\n    cell_timeout_sec: 1800\n    notebook_timeout_sec: 2400\n    description: \"Deep Research queries can take up to 30+ minutes\"\n\n  quickstarts/Get_Started_Nano_Banana.ipynb:\n    cell_timeout_sec: 180\n    notebook_timeout_sec: 1800\n    description: \"Image generation and multi-turn image editing\"\n\n  quickstarts/Get_started_thinking.ipynb:\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1800\n    description: \"Extended thinking generation chains can take up to 10 minutes per cell\"\n\n  quickstarts/Get_started_thinking_REST.ipynb:\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1200\n    description: \"Thinking REST endpoint multi-turn analysis\"\n\n  quickstarts/Get_started_Omni.ipynb:\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1200\n    description: \"Omni multimodal model processing\"\n\n  quickstarts/Video_understanding.ipynb:\n    long_running: true\n    cell_timeout_sec: 600\n    notebook_timeout_sec: 1500\n    description: \"Video upload, processing, and multi-turn frame analysis\"\n\n  quickstarts/Inference_tiers.ipynb:\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1200\n    description: \"Multi-tier model benchmarking and latency comparison\"\n\n  quickstarts/Get_started.ipynb:\n    cell_timeout_sec: 300\n    notebook_timeout_sec: 1200\n    description: \"Full tour of multimodal features across large files\"\n\n  examples/Virtual_Try_On.ipynb:\n    skip_notebook: true\n    skip_reason: \"Requires interactive Colab Vertex AI auth (auth.authenticate_user)\"\n\n  examples/Google_IO2025_Live_Coding.ipynb:\n    skip_notebook: true\n    skip_reason: \"Historical event notebook kept frozen with original Google I/O 2025 models\"\n\n  examples/Book_illustration.ipynb:\n    cell_timeout_sec: 360\n    notebook_timeout_sec: 1800\n    description: \"Multimodal audio, TTS, image generation, and MoviePy mix\"\n\n  examples/gemini_google_adk_model_guardrails.ipynb:\n    allow_security_demo: true\n    description: \"Demonstrates model guardrails against prompt injection and backdoors\"\n\n  examples/LiveAPI_plotting_and_mapping.ipynb:\n    allow_dynamic_exec: true\n    allow_security_demo: true\n    description: \"Demonstrates live plotting and mapping using code execution tools\"\n\n  examples/prompting/Basic_Code_Generation.ipynb:\n    allow_dynamic_exec: true\n    allow_security_demo: true\n    description: \"Demonstrates generating and executing Python code via exec()\"\n\n<!-- File: tools/nb_tester/README.md (Tokens: ~1563 | Category: plugin-manifest) -->\n# 🧪 Gemini API Cookbook Notebook Testing & Regression Suite\n\nAn automated, security-gated test runner and semantic regression evaluator designed specifically for the Jupyter/Colab notebooks in the [Gemini API Cookbook](https://github.com/google-gemini/cookbook).\n\n---\n\n## 🌟 Key Features\n\n1. **🔒 Multi-Layer Security Architecture (Preventing RCE & Key Theft)**:\n   - **Level 1 (Static AST Scanner)**: Fast, zero-secret AST checks for forbidden system calls, reverse shells, and raw environment dumps.\n   - **Level 2 (Gemini AI Security Auditor)**: Semantic code review with structured JSON output before any code execution to detect subtle backdoors, malicious `%pip` dependencies, or data exfiltration.\n   - **Zero-Disk-Tampering Colab Mock**: Injects a virtual `google.colab.userdata` module into the kernel namespace in memory, keeping notebooks clean and keys secure.\n2. **⚖️ Semantic Output Regression Judging**:\n   - Compares newly generated outputs with the saved reference outputs in the repository.\n   - Uses Gemini AI Judge to separate normal non-deterministic phrasing differences (`SLIGHT_VARIATION`) from true broken answers or hallucinations (`REGRESSION`).\n3. **🌐 Google Search Grounding Verification**:\n   - For real-time and time-evolving queries (e.g. sports scores, weather, current events), uses Gemini with the Google Search tool to double-check that new answers are factually true today.\n4. **📋 Declarative Rules & Exception Registry (`rules/default_rules.yaml`)**:\n   - Easily configure cell-level actions (e.g. skipping interactive `input()` cells) and per-notebook timeouts.\n5. **🎯 Family-Aware Dynamic Model Identifier Override (`--model <name>`)**:\n   - Test the entire cookbook (or specific notebooks) against candidate or pre-release models (e.g. `gemini-4-hydrogen`, `gemini-3.8-flash`, `gemini-3.1-pro-preview`) by dynamically overriding `MODEL_ID` in memory across compatible cells without touching disk.\n   - Automatically preserves specialized non-text models (`-live`, `-tts`, `-image`, `embedding`, `veo`, `lyria`, `transcribe`) unless the override model itself belongs to that same model family.\n6. **📊 CI & Pull Request Integration**:\n   - Generates persistent JSON reports under `reports/` and auto-appends formatted Markdown tables to `$GITHUB_STEP_SUMMARY`.\n   - Returns clean exit codes (`0` on pass, `1` on failure) for automated gating.\n7. **🔍 Dry-Run Mode**:\n   - Test rule configurations, AST checks, model overrides, and syntax parsing without altering files, spinning up kernels, or consuming API tokens.\n8. **🔁 Automatic Cell-Level Retry & Exponential Backoff**:\n   - Automatically retries failed cells (up to 3 times by default with exponential backoff) on transient API errors (429, 503, timeouts) before failing, preventing flaky CI runs while skipping non-retryable syntax errors. Configurable via `--max-retries` CLI flag or `rules/default_rules.yaml`.\n\n---\n\n## 🛠️ System Prerequisites (Local Execution)\n\nIn Google Colab, `ffmpeg`, `jq`, and `curl` are pre-installed in the default runtime container (and `poppler-utils` is installed via `!apt-get install -y -q poppler-utils` inside `quickstarts/PDF_Files.ipynb`).\n\nWhen running `tools/nb_tester` locally on a Linux/macOS workstation or headless CI runner (where notebooks do not execute as `root`), install the following system packages first so audio, video, PDF (`pdf2image` / `pdftoppm`), and REST (`curl` + `jq`) notebooks execute cleanly:\n\n```bash\n# Ubuntu / Debian / gLinux\nsudo apt-get update && sudo apt-get install -y ffmpeg poppler-utils jq curl\n```\n\n---\n\n## 🚀 Quickstart & Usage\n\n### 1. Dry-Run Mode (Safe simulation)\n```bash\npython3 -m tools.nb_tester.cli --notebook quickstarts/Counting_Tokens.ipynb --dry-run\n```\n\n### 2. Security Audit Only (No code execution)\n```bash\npython3 -m tools.nb_tester.cli --notebook quickstarts/Prompting.ipynb --security-only\n```\n\n### 3. Test a Single Notebook with Live Execution & AI Judge\n```bash\nexport GEMINI_API_KEY=\"your-api-key\"\npython3 -m tools.nb_tester.cli --notebook quickstarts/Counting_Tokens.ipynb\n```\n\n### 4. Test Only Changed Notebooks in a PR / Git Branch\n```bash\npython3 -m tools.nb_tester.cli --changed\n```\n\n### 5. Test Notebooks with Dynamic Model Override\n```bash\n# Run a specific quickstart against a candidate/preview model\npython3 -m tools.nb_tester.cli --notebook quickstarts/Get_started_thinking.ipynb --model gemini-3.1-pro-preview\n\n# Run all quickstarts with model override in parallel\npython3 -m tools.nb_tester.cli --all --model gemini-3.7-flash --workers 4\n```\n\n### 6. Run Full Suite in Parallel\n```bash\npython3 -m tools.nb_tester.cli --all --workers 4\n```\n\n---\n\n## ⚙️ Configuration & Exception Rules\n\nRules are declared in `tools/nb_tester/rules/default_rules.yaml`.\n\n```yaml\nglobal_defaults:\n  cell_timeout_sec: 90\n  notebook_timeout_sec: 600\n  default_strategy: \"semantic_llm\"\n\nnotebooks:\n  quickstarts/Grounding.ipynb:\n    cells:\n      - match: \"client.models.generate_content\"\n        strategy: \"grounded_factual\"\n        description: \"Verify dynamic search output using Google Search\"\n\n  quickstarts/Interactive_Chat.ipynb:\n    cells:\n      - match: \"input(\"\n        action: \"skip\"\n        reason: \"Interactive user input not supported in headless CI\"\n```\n\n---\n\n## 🏗️ Architecture & Modules\n\n```\ntools/nb_tester/\n├── config.py             # Centralized models, timeouts, and GEMINI_API_KEY resolution\n├── logger.py             # Structured logging with complete LLM prompt/response tracking\n├── security_scanner.py   # Level 1: Deterministic AST & regex scanner\n├── ai_security_auditor.py# Level 2: Gemini AI Semantic Security Auditor\n├── rules.py              # Declarative rules engine and matcher\n├── model_override.py     # In-memory MODEL_ID override transformer & preamble injector\n├── executor.py           # nbclient kernel executor with in-memory Colab mock\n├── comparator.py         # Output snapshot extractor and strategy router\n├── llm_judge.py          # Level 3: Semantic output regression judge\n├── grounded_verifier.py  # Real-time fact-checking via Google Search Grounding\n├── reporter.py           # Multi-format report builder (JSON, Step Summary, Terminal)\n├── cli.py                # Command-line interface entry point\n└── rules/\n    └── default_rules.yaml# Default rule definitions and exceptions\n```\n\n<!-- File: tools/README.md (Tokens: ~1585 | Category: plugin-manifest) -->\n# Gemini API Cookbook Quality Assurance & Linting Tools\n\nThis directory contains standalone tools for formatting, linting, and maintaining Jupyter/Colab notebooks in the [Gemini API Cookbook](https://github.com/google-gemini/cookbook).\n\nThese tools are natively hosted in this repository to provide fast, zero-dependency validation tailored specifically to the Gemini SDK and cookbook style guidelines.\n\n---\n\n## Tools Overview\n\n| Tool | Script | Description |\n| :--- | :--- | :--- |\n| **`nblint`** | `tools/nblint_cli.py` | Lints notebooks for licensing, structure, style, SDK best practices, and model selectors. |\n| **`nbfmt`** | `tools/nbfmt_cli.py` | Automatically formats notebook JSON, standardizes metadata, strips empty cells, and aligns code formatting. |\n| **`readme_links`** | `tools/check_readme_links.py` | Validates that new/modified notebooks are linked in section Table of Contents READMEs. |\n| **`check_all_links`** | `tools/check_all_links.py` | Audits internal paths, anchors, blob URLs, and external links across `.md` and `.ipynb` files. |\n| **`config`** | `tools/config.py` | Central configuration file containing model hierarchies, wordlists, exclusions, and URL rules. |\n\n---\n\n## 1. Quickstart Usage\n\n### Linting Notebooks\n```bash\n# Lint a specific notebook\npython tools/nblint_cli.py quickstarts/Get_started.ipynb\n\n# Lint multiple notebooks or directories\npython tools/nblint_cli.py quickstarts/**/*.ipynb examples/**/*.ipynb\n\n# Perform a dry-run check\npython tools/nblint_cli.py --dry-run quickstarts/Get_started.ipynb\n\n# Specify custom branch or repository\npython tools/nblint_cli.py --repo=google-gemini/cookbook --branch=main path/to/notebook.ipynb\n```\n\n### Formatting Notebooks\n```bash\n# Format a specific notebook (modifies file in place)\npython tools/nbfmt_cli.py quickstarts/Get_started.ipynb\n\n# Test if notebooks are properly formatted (without modifying, returns non-zero on unformatted)\npython tools/nbfmt_cli.py --test quickstarts/**/*.ipynb\n\n# Format all notebooks in the repo\npython tools/nbfmt_cli.py quickstarts/**/*.ipynb examples/**/*.ipynb\n```\n\n### Checking Table of Contents README Links\n```bash\n# Check if a specific notebook is linked in its folder/section README.md\npython tools/check_readme_links.py quickstarts/Get_started.ipynb\n\n# Audit all notebooks in the repo\npython tools/check_readme_links.py --all\n```\n\n### Verifying Internal and External Links\n```bash\n# Validate internal links and anchors on specific files (fast CI check)\npython tools/check_all_links.py quickstarts/Get_started.ipynb README.md\n\n# Validate all git-modified files against upstream/main\npython tools/check_all_links.py --changed\n\n# Full repository audit of all internal relative links and anchor slugs\npython tools/check_all_links.py\n\n# Full repository audit including live external HTTP/HTTPS health checks\npython tools/check_all_links.py --all\n```\n\n---\n\n## 2. Lint Rules Reference\n\n### Python Syntax Rules (`tools/nblint/rules/syntax.py`)\n- **`syntax::code_cell`**: Parses code cells, including `%%time` bodies, with `ast.parse` after neutralizing IPython magics and shell escapes. Other `%%` cell magics are skipped. Reports the cell index and original line of any `SyntaxError`.\n\n### Structure Rules (`tools/nblint/rules/structure.py`)\n- **`structure::copyright`**: Verifies that cell 0 contains a valid Google / Gemini copyright statement (`##### Copyright 2026 Google LLC.`).\n- **`structure::license`**: Verifies that the notebook contains a collapsed Apache 2.0 license code cell with `# @title Licensed under the Apache License`.\n- **`structure::colab_button`**: Checks for the \"Open in Colab\" badge and verifies that its destination URL matches `https://colab.research.google.com/github/<repo>/blob/<branch>/<path>`. Automatically adjusts for redirect stubs.\n- **`structure::next_steps`**: Emits a warning if a closing section is missing. Accepted headings: \"Next steps\", \"What's next\", \"Learn more\" / \"Learning more\", \"Further reading\" / \"Further resources\" or \"Conclusion\".\n\n### Style & Language Rules (`tools/nblint/rules/style.py`)\n- **`style::inclusive_language`**: Flags discouraged terminology (`blacklist`, `whitelist`, `master`, `slave`) and suggests modern alternatives. **Note**: The word `\"native\"` is deliberately allowed because terms like *\"native audio\"*, *\"native TTS\"*, and *\"native multimodal\"* are standard Gemini API features.\n- **`style::second_person`**: Ensures narrative explanations in markdown use second person (*you*) rather than first person (*we*). Prompt strings, quoted examples, and code comments are ignored.\n- **`style::line_length`**: Warns when code lines exceed 100 characters (ignoring URLs, form annotations, and long multiline strings).\n\n### Gemini SDK & API Best Practices (`tools/nblint/rules/gemini.py`)\n- **`gemini::pip_magic`**: Enforces `%pip install` instead of `!pip install` for reliable kernel-level package installation.\n- **`gemini::sdk_package`**: Enforces the official `from google import genai` (`google-genai`) SDK, flagging deprecated `google.generativeai`.\n- **`gemini::api_key_secret`**: Checks that notebooks retrieve API keys from `userdata.get('GEMINI_API_KEY')` rather than the legacy `GOOGLE_API_KEY` secret.\n- **`gemini::hardcoded_api_key`**: Scans all cells for accidental plaintext Google/Gemini API keys (legacy `AIza...` and new `AQ.Ab8...` formats) to prevent credential leakage.\n\n### Model Selector Validation (`tools/nblint/rules/model_selector.py`)\n- **`gemini::model_selector`**:\n  - Verifies that model selectors use the canonical Colab form pattern:\n    ```python\n    MODEL_ID = \"gemini-3.7-flash\" # @param [\"gemini-3.1-pro-preview\", \"gemini-3.7-flash\", \"gemini-3.5-flash-lite\"] {\"allow-input\":true, isTemplate: true}\n    ```\n  - Verifies that the default assigned model exists in the option list.\n  - Verifies that models in the list are sorted in logical order from most capable to least capable: **current generation (Pro $\\rightarrow$ Flash $\\rightarrow$ Flash-Lite)**, followed by **previous generation (e.g. Gemini 3.x)**.\n\n---\n\n## 3. Configuration & Exclusions\n\nAll configurable settings are consolidated in `tools/config.py`:\n- **`EXCLUDED_NOTEBOOKS`**: List of files skipped during automated lint runs (e.g. `quickstarts/Template.ipynb`).\n- **`REDIRECT_KEYWORDS`**: Keywords used to automatically detect redirection stubs (e.g. `gemini-robotics-er.ipynb`) and apply lenient rules.\n- **`get_model_sort_key(model_name)`**: Ranking algorithm for model selector ordering.\n- **`INCLUSIVE_LANGUAGE_WORDLIST`**: Mapping of discouraged terms to replacements.\n</yakaai_skills>"}