⌂ Home
Gemini CLI: Terminal AI Agent Foundations
Gemini CLI Track
⏰ 25-35 min Module 1 of 18 📺 Windows-first
🔮
Gemini CLI Track — M00: Setup & First Run You'll install Gemini CLI, authenticate with your Google account, and run your first five useful commands — all on a real FastAPI project called TaskFlow. No toy examples.

Setup & First Run

By the end of this module you will have Gemini CLI installed, authenticated, and producing useful analysis on a real codebase. We are not going to use a "hello world" example — we're going to use TaskFlow, the project you'll work with throughout this entire course.

What We're Building

Analogy First

Before Gemini CLI, asking AI to help with your code was like describing your car problem over the phone to a mechanic who has never seen your car. You describe the noise, they give generic advice, and you still have to do all the repair work yourself. The pain was that the AI lived in a different world from your actual files. Gemini CLI changes this: it's like handing the mechanic your car keys — they can open the hood, run diagnostics, and actually fix things. The conversation and the actions happen in the same garage.

The reference project for this course is TaskFlow — a task management REST API built with FastAPIA modern Python web framework for building REST APIs. Automatically generates interactive API documentation at /docs. Fast because it uses async I/O and Pydantic for validation. and SQLiteA lightweight file-based SQL database. No separate server needed — the database is stored in a single .db file. Perfect for development and small applications.. Here's what you'll be working with:

sample-project/taskflow/ │—— main.py # FastAPI app entry point — 3 routers registered here │—— models.py # SQLAlchemy models: User, Task, Tag (+ task_tags join) │—— schemas.py # Pydantic v2 schemas for request/response validation │—— auth.py # JWT helpers: hash_password, verify_password, get_current_user │—— database.py # SQLAlchemy engine + get_db() session dependency │—— GEMINI.md # Project context file — loaded automatically by Gemini CLI │—— requirements.txt # fastapi, uvicorn, sqlalchemy, pydantic, python-jose, passlib │—— .env.example # SECRET_KEY, DATABASE_URL, ACCESS_TOKEN_EXPIRE_MINUTES │—— Dockerfile # Container build for deployment │—— routers/ │ │—— users.py # POST /users/register, POST /users/login │ │—— tasks.py # Full CRUD for /tasks/ (JWT auth required) │ ├—— tags.py # GET/POST/DELETE /tags/ (JWT auth required) ├—— tests/ ├—— test_tasks.py # Pytest test suite

TaskFlow has 11 API endpoints, JWT authentication, SQLAlchemy ORM, Pydantic v2 validation, and a test suite. It is complex enough to be a realistic teaching tool but small enough to understand completely. You'll use Gemini CLI to explore it, extend it, test it, and eventually deploy it.

Why This Matters

Learning AI tooling on toy "hello world" examples creates a false impression. Real codebases have interdependencies, authentication flows, shared schemas, and business logic spread across files. TaskFlow models that complexity at a learnable scale. Every command in this course produces real, useful output — not placeholder text.

Install Gemini CLI

What You're Installing

Gemini CLI is an open-source npm packageA package distributed through npm (Node Package Manager). When installed globally with -g, it registers a command you can run from any terminal. You don't need to know JavaScript to use it. published by Google at @google/gemini-cli. It requires Node.js 18+ but you write zero JavaScript — it's a terminal command that calls the Gemini API. Prerequisites: Node.js 18+, npm 9+, a Google account (free tier) or Gemini API key.

📺 Windows — PowerShell 7+ recommended
WHAT: Check if Node.js is installed. If not, use WinGet (built into Windows 11) to install it.
powershell
# Check Node.js version (need 18+)
node --version

# If not installed, use WinGet (Windows 11 / Windows 10 with App Installer)
winget install OpenJS.NodeJS.LTS

# Alternative: download from https://nodejs.org/en/download/
WHAT: Fix the PowerShell execution policy so npm-installed tools can run. This is a one-time fix. GOTCHA: Without this step, running gemini may fail with "gemini is not recognized" even after install.
powershell (run as Administrator)
# Fix execution policy (one-time setup, run as Administrator)
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

# Install Gemini CLI globally
npm install -g @google/gemini-cli

# Verify installation
gemini --version
Expected output Running gemini --version should print something like 0.1.x. If you see "command not found", close and reopen your terminal — npm's global bin folder may need a fresh PATH.
Windows Gotcha: Execution Policy

PowerShell's default execution policyA security setting that controls which PowerShell scripts can run. "Restricted" (default) blocks all scripts. "RemoteSigned" allows locally created scripts and signed scripts from the internet — the right balance for development. is "Restricted", which blocks npm shims. The command above sets it to "RemoteSigned" — this means locally written scripts can run, but scripts downloaded from the internet must be digitally signed. This is safe for development machines.

WHAT: Install Node.js via Homebrew, then install Gemini CLI globally.
bash (macOS Terminal)
# Install Homebrew if needed
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# Install Node.js LTS
brew install node

# Install Gemini CLI globally
npm install -g @google/gemini-cli

# Verify
gemini --version
bash (Linux)
# Install Node.js via NodeSource (Ubuntu/Debian)
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejs

# Fix npm global permissions (avoid sudo npm install)
mkdir -p ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc

# Install Gemini CLI
npm install -g @google/gemini-cli

# Verify
gemini --version

Authenticate

Gemini CLI offers two authentication paths. For this course we use the Google account (OAuth) path — it gives you the free tier without a credit card.

WHAT: Run the login command. It opens your browser for Google OAuth, stores the token locally, and you're done. WHY: The token is stored in your OS credential store — you don't manage it manually.
powershell / terminal
gemini auth login
# Opens browser → Sign in with Google → Authorize → Done
# Token stored in ~/.gemini/credentials (Linux/macOS) or %APPDATA%\gemini\credentials (Windows)
Expected output Terminal prints: Authentication successful. You are now logged in as your@email.com
powershell
# Get API key from https://aistudio.google.com/app/apikey
# Set as environment variable (add to your PowerShell profile for persistence)
$env:GEMINI_API_KEY = "AIza..."

# Or set permanently in Windows environment variables:
[System.Environment]::SetEnvironmentVariable("GEMINI_API_KEY","AIza...","User")

Free Tier Limits

Tier Model Rate Limit Daily Limit Cost
Free Google Account Gemini 2.5 Flash 10 req/min 1,500 req/day $0
Paid API Key (Pay-as-go) Gemini 2.5 Flash 1,000 req/min Unlimited $0.075/1M tokens in
Paid API Key (Pro) Gemini 2.5 Pro 360 req/min Unlimited $1.25/1M tokens in

For this course, the free tier is more than sufficient. At 10 req/min and 1,500/day, you can run about 50 full lab sessions without hitting limits.

First Look at TaskFlow

Analogy First

A new developer joining a project used to spend their first week reading docs, tracing call stacks, and asking senior devs "what does this do?" The pain was that institutional knowledge lived in people's heads, not in the code. Gemini CLI compresses that week into minutes by letting you ask the codebase directly: "What does this project do? Show me the auth flow. What would break if I changed this model?" TaskFlow is that new project, and you're the new developer with an AI pair.

Navigate to the TaskFlow directory and ask Gemini CLI to explain the project. When you run gemini inside a directory that has a GEMINI.md file, it automatically loads that file as context before answering.

WHAT: Change to the TaskFlow directory and launch Gemini CLI. Gemini will auto-read GEMINI.md and scan nearby files. WHY: Running Gemini from inside the project directory gives it filesystem context — it knows which files exist and can read them on demand.
powershell
cd sample-project\taskflow
gemini "What does this project do?"
bash
cd sample-project/taskflow
gemini "What does this project do?"
PowerShell — sample-project/taskflow
PS>gemini "What does this project do?"
✦ Reading GEMINI.md...
TaskFlow is a REST API for managing personal tasks. It's built
with FastAPI + SQLite and has three main resource types:
 
Users — register and login (JWT authentication)
Tasks — CRUD with priority (low/medium/high) and due dates
Tags — labels that attach to tasks via many-to-many
 
All task and tag routes require a Bearer token from POST /users/login.
Start server: uvicorn main:app --reload → docs at /docs
Press ▶ to watch Gemini respond
What Just Happened?

Gemini CLI automatically found and read GEMINI.md in the current directory. That file contains a structured description of the project — endpoints, file roles, auth pattern, dev commands. Gemini used it to give you a specific, accurate answer instead of generic advice. In M02 you'll learn to write your own GEMINI.md from scratch.

Context Loading with @-mentions

Technical Definition

A context mention (@filename) tells Gemini CLI to read a specific file and include its content as part of your prompt. Without @, Gemini only has what's in GEMINI.md and its general knowledge. With @models.py, it has the exact current content of that file. The difference between "I know Python SQLAlchemy" and "I can see your Task model right now" is the difference between advice and answers.

Without @-mention

gemini "Explain the Task model"

⚠ Generic SQLAlchemy answer
May hallucinate field names
Doesn't know your priority values

With @-mention

gemini "@models.py Explain the Task model"

✅ Sees your exact fields
Knows priority = "low/medium/high"
Sees the task_tags join table

Single File: @models.py

WHAT: Load a specific file into context before asking your question. Gemini reads the file, then answers based on its actual content. GOTCHA: The path is relative to your current working directory.
powershell
# Ask about the Task model using the actual file
gemini "@models.py Explain the Task model and all its fields"

# Ask about authentication by loading the real auth.py
gemini "@auth.py How does get_current_user verify a JWT token?"
bash
gemini "@models.py Explain the Task model and all its fields"
gemini "@auth.py How does get_current_user verify a JWT token?"

Multi-file: Cross-file Analysis

WHAT: Mention multiple files to ask cross-cutting questions. WHY: TaskFlow has schemas in schemas.py and models in models.py — they need to stay in sync. This is the kind of check a senior engineer does but rarely documents.
powershell
# Compare models and schemas for sync issues
gemini "@models.py @schemas.py Are the Task model fields and Task schema fields in sync? List any mismatches."

# Understand what routes are protected
gemini "@main.py @routers/tasks.py Which routes require authentication and how is it enforced?"
bash
gemini "@models.py @schemas.py Are the Task model fields and Task schema fields in sync? List any mismatches."
gemini "@main.py @routers/tasks.py Which routes require authentication and how is it enforced?"
What Just Happened?

You just ran a cross-file consistency check in one command. Without Gemini CLI, this means reading two files manually and comparing fields by hand — a task that takes 5-10 minutes and is easy to get wrong. With @models.py @schemas.py, Gemini reads both files and does the comparison in seconds. This pattern scales to any number of files.

Headless Mode

Technical Definition

Headless mode runs Gemini CLI non-interactively — it executes a single prompt, prints the output, and exits. This is the -p flag (short for --prompt) combined with --no-interactive. Use it in shell scripts, CI pipelines, git hooks, and any automation where you need AI analysis without a conversation. The output goes to stdout so you can pipe it, redirect it, or capture it in a variable.

WHAT: The -p flag provides the prompt directly on the command line. --no-interactive (or --yolo for auto-approve) prevents Gemini from asking follow-up questions. WHY: In CI you can't have an interactive session — the process must start, do work, and exit with a status code.
powershell
# List all API endpoints (no interactive session)
gemini -p "List all API endpoints in @main.py @routers/tasks.py @routers/users.py @routers/tags.py" --no-interactive

# Use output in a PowerShell script
$endpoints = gemini -p "List only the HTTP method and path for each endpoint in @routers/tasks.py" --no-interactive
Write-Output "Found endpoints:`n$endpoints"

# Pipe to a file for documentation
gemini -p "Generate a markdown table of all TaskFlow API endpoints from @main.py" --no-interactive | Out-File -FilePath api-docs.md
bash
# List all API endpoints
gemini -p "List all API endpoints in @main.py @routers/tasks.py @routers/users.py @routers/tags.py" --no-interactive

# Capture in a variable
ENDPOINTS=$(gemini -p "List only the HTTP method and path for each TaskFlow endpoint" --no-interactive)
echo "Found endpoints: $ENDPOINTS"

# Pipe to file
gemini -p "Generate markdown docs for the TaskFlow API from @main.py" --no-interactive > api-docs.md
Why It Matters

Headless mode is how Gemini CLI moves from "a tool you use manually" to "a tool woven into your workflow." A pre-commit hook that analyzes your staged diff. A CI step that checks whether new endpoints added a security test. A nightly job that updates your API documentation. All of these use headless mode. M14 of this course is dedicated to CI/CD automation with Gemini CLI — everything there builds on this pattern.

Rate Limits & Quotas

Free Tier Usage Meter

Per-minute requests (10 RPM limit)0 / 10
Daily requests (1,500 req/day limit)0 / 1500
Press ▶ to simulate a busy session

Handling 429 Errors

When you hit the per-minute limit, Gemini CLI returns a 429 Too Many RequestsAn HTTP status code meaning "you've sent too many requests in a given time period." The server includes a Retry-After header telling you how many seconds to wait. error. Here's how to handle it gracefully:

powershell — retry with backoff
# PowerShell: retry Gemini CLI with exponential backoff
function Invoke-GeminiWithRetry {
    param([string]$Prompt, [int]$MaxRetries = 3)
    $delay = 10  # seconds
    for ($i = 0; $i -lt $MaxRetries; $i++) {
        $result = gemini -p $Prompt --no-interactive 2>&1
        if ($LASTEXITCODE -eq 0) { return $result }
        if ($result -match "429") {
            Write-Warning "Rate limited. Waiting ${delay}s before retry $($i+1)..."
            Start-Sleep -Seconds $delay
            $delay *= 2  # exponential backoff: 10s -> 20s -> 40s
        } else {
            throw $result
        }
    }
    throw "Max retries exceeded"
}

# Usage
$analysis = Invoke-GeminiWithRetry -Prompt "@routers/tasks.py Explain the create_task endpoint"
Practical Rate-Limit Patterns
  • Batch your questions: Instead of 5 separate prompts, ask "answer all of these: 1) ... 2) ... 3) ..." in one request.
  • Use GEMINI.md for context: Background info in GEMINI.md is loaded once per session, not once per prompt.
  • Switch to Flash for routine tasks: Flash is faster and cheaper — save Pro for architecture decisions.
  • The daily limit resets at midnight Pacific time (UTC-8 or UTC-7 during DST).

Lab: Your First 5 Commands on TaskFlow

Complete all five commands in order. Each one teaches a different Gemini CLI capability using the real TaskFlow codebase. Run these from inside the sample-project/taskflow/ directory.

Understand the project at a high level

powershell
gemini "What does this project do? Summarize each file in one sentence."
Expected: A bulleted summary mentioning main.py, models.py, auth.py, database.py, schemas.py, and the routers. If Gemini says "I don't see any files" — make sure you're inside the taskflow directory and that GEMINI.md exists.

Explore a specific model with @-mention

powershell
gemini "@models.py What fields does the Task model have? What are the valid priority values?"
Expected: Gemini lists all Task fields (id, title, description, completed, priority, due_date, created_at, updated_at, owner_id, tags) and correctly states priority values are "low", "medium", or "high" (from the string default in the model).

Cross-file analysis: auth flow

powershell
gemini "@auth.py @routers/users.py Trace the complete flow from a user calling POST /users/login to receiving a JWT token. Include every function called."
Expected: Gemini traces: login() → verify_password() → create_access_token() → returns Token schema with access_token and token_type. Should mention OAuth2PasswordRequestForm, bcrypt verification, and the HS256 JWT algorithm.

Headless mode: capture output

powershell
gemini -p "List all 11 TaskFlow API endpoints as: METHOD /path — description" --no-interactive
bash
gemini -p "List all 11 TaskFlow API endpoints as: METHOD /path — description" --no-interactive
Expected: 11 lines covering POST /users/register, POST /users/login, GET/POST /tasks/, GET/PATCH/DELETE /tasks/{id}, GET/POST /tags/, DELETE /tags/{id}, GET /health. Gemini should have read this from GEMINI.md's endpoint table.

Ask a "what would break?" question

powershell
gemini "@models.py @schemas.py @routers/tasks.py What would break if I added a required 'status' field to the Task model? List every file that would need changes."
Expected: Gemini identifies changes needed in models.py (add field), schemas.py (TaskBase, TaskCreate, TaskUpdate), possibly a database migration, and notes that existing tasks in the DB would fail validation. This shows Gemini reasoning across multiple files.
What You Just Proved

In five commands you learned more about TaskFlow than you could from 30 minutes of reading the code manually. Command 5 especially demonstrates why Gemini CLI is different from a search engine: it reasons about impact, not just content. That kind of analysis is what makes it an agent, not a file reader.

Knowledge Check

Test your understanding of Gemini CLI setup and first commands.

1. You installed Gemini CLI on Windows with npm install -g @google/gemini-cli but running gemini gives "command not recognized". What is the most likely cause?

Node.js is not in PATH
PowerShell execution policy is set to Restricted
The npm package name is wrong
You need to restart your computer

2. You run gemini "@models.py Explain the Task model" from the TaskFlow directory. What does the @models.py part do?

It runs models.py before asking the question
It reads the file content and includes it in the prompt sent to Gemini
It imports models.py as a Python module
It searches the file for the word "Task"

3. What is the free tier rate limit for Gemini CLI when using Google account authentication?

60 requests/minute, 1,000 requests/day
100 requests/minute, unlimited/day
10 requests/minute, 1,500 requests/day
5 requests/minute, 500 requests/day

4. Which flag combination runs Gemini CLI non-interactively (good for scripts and CI)?

gemini --script "your prompt"
gemini --batch "your prompt"
gemini -p "your prompt" --no-interactive
gemini --run "your prompt"

5. When you run gemini "What does this project do?" inside the TaskFlow directory, what context does Gemini automatically load?

All Python files in the directory
Nothing — you must explicitly @-mention every file
GEMINI.md (the project context file, if it exists)
requirements.txt only

Quiz Complete!

Ready for M01: Prompting Patterns & Context →