feat: add AI category with Claude Code, Codex CLI, Gemini CLI, OpenClaw, ChatGPT, Gemma4 cheatsheets

- Add new AI category to index_categories (above Programming)
- Add cheatsheets: Claude Code, Codex CLI, Gemini CLI, OpenClaw
- Move ChatGPT and Gemma4 to AI category
- Add SVG icons for claude-code, codex-cli, gemini-cli, openclaw (1em sizing)
This commit is contained in:
Fechin committed 2026-04-03 18:12:55 +08:00
1 parent 21e17efe52
commit a875ac1204
11 files changed
+3588 -2

No files matched your search

+2 -2
View File
@@ -8,7 +8,7 @@ tags:
- Prompts
- Tips
categories:
- Toolkit
- AI
intro: This cheat sheet lists out prompts and tips from all over the world on how to use ChatGPT effectively
plugins:
- copyCode
@@ -1014,4 +1014,4 @@ Scenario:
em { font-size: 0.785em; }
strong {font-weight: 400;}
ul.collapsible > li > pre { padding-left: 0; padding-right: 0; font-size: 0.925em;}
</style>
</style>
+927
View File
@@ -0,0 +1,927 @@
---
title: Claude Code
date: 2026-04-03 12:00:00
background: bg-[#cc785c]
tags:
- AI
- CLI
- Anthropic
- coding
- assistant
categories:
- AI
intro: |
[Claude Code](https://code.claude.com) is an agentic AI coding tool by Anthropic — reads your codebase, edits files, runs commands, and integrates with your development tools.
plugins:
- copyCode
---
## Getting Started
### Installation {.row-span-2}
#### macOS / Linux / WSL
```bash
$ curl -fsSL https://claude.ai/install.sh | bash
```
#### Windows PowerShell
```powershell
> irm https://claude.ai/install.ps1 | iex
```
#### Homebrew (macOS)
```bash
$ brew install --cask claude-code
```
#### WinGet (Windows)
```powershell
> winget install Anthropic.ClaudeCode
```
Native install auto-updates. Homebrew/WinGet require `brew upgrade claude-code` or `winget upgrade Anthropic.ClaudeCode` to update.
Windows requires [Git for Windows](https://git-scm.com/downloads/win).
### First Session
```bash
$ cd your-project
$ claude
```
- Log in on first run (Claude Pro / Max / Team / Enterprise or Anthropic Console)
- Type `/help` for all commands
- Type `/resume` to continue a prior conversation
- Press `?` to see keyboard shortcuts
- Type `exit` or press `Ctrl+D` to quit
### Key Concepts {.secondary}
| Concept | Description |
| --------------- | ----------------------------------------------------- |
| Agent loop | Claude reads, edits files, runs commands, and repeats |
| CLAUDE.md | Persistent instructions Claude reads every session |
| Auto memory | Claude saves learnings across sessions automatically |
| Skills | Custom `/commands` for reusable workflows |
| Hooks | Shell scripts triggered at lifecycle events |
| MCP | Connect Claude to external tools and APIs |
| Permission mode | Controls what Claude can do without asking |
{.bold-first}
### Common Prompts
- `what does this project do?`
- `find the bug causing the login error`
- `write unit tests for the auth module`
- `refactor this to use async/await`
- `commit my changes with a descriptive message`
- `create a PR and describe my changes`
- `review my changes for security issues`
- `add input validation to the signup form`
{.cols-2 .marker-none}
## CLI Commands {.cols-2}
### Session Commands {.row-span-3}
| Command | Description |
| --------------------------- | --------------------------------- |
| `claude` | Start interactive session |
| `claude "task"` | Start with initial prompt |
| `claude -p "query"` | Print response and exit |
| `claude -c` | Continue most recent conversation |
| `claude -r [name]` | Resume session by name or ID |
| `claude -n "name"` | Name this session |
| `claude -w [name]` | Start in isolated git worktree |
| `claude update` | Update to latest version |
| `claude -v` | Show version number |
| `claude doctor` | Check installation health |
| `claude auto-mode defaults` | Print auto mode classifier rules |
| `claude agents` | List configured subagents |
{.show-header}
#### Auth Commands
| Command | Description |
| ----------------------------- | ------------------------------ |
| `claude auth login` | Sign in to account |
| `claude auth login --console` | Sign in with Anthropic Console |
| `claude auth logout` | Sign out |
| `claude auth status` | Show auth status |
#### MCP Commands
| Command | Description |
| -------------------------- | -------------------------- |
| `claude mcp list` | List configured servers |
| `claude mcp add <n> <cmd>` | Add a stdio MCP server |
| `claude mcp get <name>` | Show server details |
| `claude mcp remove <name>` | Remove a server |
| `claude mcp serve` | Start Claude as MCP server |
#### Plugin Commands
| Command | Description |
| ------------------------------ | ---------------------- |
| `claude plugin install <name>` | Install a plugin |
| `claude plugin list` | List installed plugins |
| `claude plugin remove <name>` | Remove a plugin |
### Pipe Examples
```bash
# Explain a build error
$ cat error.log | claude -p "explain the root cause"
```
```bash
# Review changed files
$ git diff main --name-only | claude -p "review for issues"
```
```bash
# Analyze logs
$ tail -200 app.log | claude -p "summarize anomalies"
```
```bash
# Save output to file
$ cat data.txt | claude -p "summarize this" > summary.txt
```
### Unix Integration
Add Claude as a linter in `package.json`:
```json {.wrap}
{
"scripts": {
"lint:ai": "claude -p 'review changes vs main, report file:line + issue'"
}
}
```
Use `--output-format` for structured output:
```bash
$ claude -p "analyze for bugs" --output-format json
```
## CLI Flags {.cols-3}
### Session & Mode {.row-span-2}
| Flag | Description |
| ----------------------- | ----------------------------------------- |
| `--model <model>` | Model alias: `sonnet`, `opus`, or full ID |
| `--permission-mode <m>` | Set permission mode at startup |
| `-c, --continue` | Load most recent conversation |
| `-r, --resume [id]` | Resume by session ID or name |
| `-n, --name <name>` | Name the current session |
| `-w, --worktree [name]` | Create isolated git worktree |
| `-p, --print` | Non-interactive print mode |
| `--effort <level>` | `low` `medium` `high` `max` |
| `--ide` | Auto-connect to IDE on startup |
| `--verbose` | Show full turn-by-turn output |
| `--debug [filter]` | Enable debug (e.g. `"api,hooks"`) |
| `--fork-session` | New ID when resuming |
| `--from-pr [num]` | Resume sessions linked to PR |
| `--version, -v` | Print version number |
{.bold-first}
### Output & Format
| Flag | Description |
| ---------------------------- | ------------------------------- |
| `--output-format` | `text` / `json` / `stream-json` |
| `--input-format` | `text` or `stream-json` |
| `--max-turns <n>` | Limit agentic turns |
| `--max-budget-usd <n>` | Spending cap (print mode) |
| `--json-schema <s>` | Validate structured output |
| `--include-partial-messages` | Stream partial chunks |
| `--no-session-persistence` | Don't save session to disk |
| `--fallback-model <m>` | Fallback when overloaded |
{.bold-first}
### Tools & Access
| Flag | Description |
| -------------------------------------- | ------------------------------ |
| `--allowedTools <tools>` | Pre-approve tools (no prompt) |
| `--disallowedTools <tools>` | Deny specific tools |
| `--tools <list>` | Restrict available tools |
| `--add-dir <dirs>` | Extra directories to access |
| `--dangerously-skip-permissions` | Bypass all permission checks |
| `--allow-dangerously-skip-permissions` | Add bypass to mode cycle |
| `--enable-auto-mode` | Add auto to Shift+Tab cycle |
| `--bare` | Minimal mode (no hooks/memory) |
| `--mcp-config <file>` | Load MCP config from file |
| `--strict-mcp-config` | Only use CLI MCP config |
{.bold-first}
### System Prompt Flags
| Flag | Behavior |
| --------------------------------- | ----------------------------- |
| `--system-prompt <text>` | Replace entire default prompt |
| `--system-prompt-file <file>` | Replace from file |
| `--append-system-prompt <text>` | Append to default prompt |
| `--append-system-prompt-file <f>` | Append from file |
{.bold-first}
Prefer `--append-*` to preserve Claude's built-in capabilities. Use `--system-prompt` only when full control is needed.
## Slash Commands {.cols-3}
### Session & Context {.row-span-2}
| Command | Description |
| ------------------ | ----------------------------------------- |
| `/clear` | Clear history (aliases: `/new`, `/reset`) |
| `/compact [focus]` | Compact context with optional focus |
| `/resume [name]` | Resume session (alias: `/continue`) |
| `/branch [name]` | Fork conversation (alias: `/fork`) |
| `/rewind` | Undo to checkpoint (alias: `/checkpoint`) |
| `/diff` | View uncommitted changes interactively |
| `/export [file]` | Export conversation as plain text |
| `/copy [N]` | Copy Nth-last response to clipboard |
| `/cost` | Show token usage stats |
| `/usage` | Show plan limits and rate limit status |
| `/context` | Visualize context window usage |
| `/btw <q>` | Side question without adding to history |
{.show-header}
### Code & Git
| Command | Description |
| --------------------- | ---------------------------------------- |
| `/plan [desc]` | Enter plan (read-only) mode |
| `/security-review` | Audit branch changes for vulnerabilities |
| `/pr-comments [PR]` | Fetch GitHub PR comments |
| `/install-github-app` | Set up GitHub Actions integration |
| `/install-slack-app` | Install Slack integration |
### Settings & Config
| Command | Description |
| ----------------- | --------------------------------------- |
| `/config` | Open settings (alias: `/settings`) |
| `/model [model]` | Change AI model |
| `/effort [level]` | Set effort: `low` `medium` `high` `max` |
| `/permissions` | Manage allow / ask / deny rules |
| `/hooks` | View configured hooks |
| `/memory` | Edit CLAUDE.md and auto memory |
| `/mcp` | Manage MCP server connections |
| `/agents` | Manage subagent configurations |
| `/skills` | List available skills |
| `/plugin` | Manage installed plugins |
| `/keybindings` | Open keybindings config file |
### Display & UI
| Command | Description |
| ----------------- | ----------------------------- |
| `/theme` | Change color theme |
| `/vim` | Toggle vim editing mode |
| `/color [color]` | Set prompt bar color |
| `/statusline` | Configure status line display |
| `/stats` | View daily usage and streaks |
| `/insights` | Analyze session patterns |
| `/fast [on\|off]` | Toggle fast mode |
| `/powerup` | Interactive feature tour |
| `/tasks` | Manage background tasks |
| `/add-dir <path>` | Add working directory |
### Help & System
| Command | Description |
| ------------------ | --------------------------------- |
| `/help` | Show available commands |
| `/init` | Generate CLAUDE.md for project |
| `/doctor` | Diagnose installation |
| `/voice` | Toggle voice dictation |
| `/schedule [desc]` | Create cloud scheduled task |
| `/login` | Sign in to account |
| `/logout` | Sign out |
| `/feedback` | Submit feedback (alias: `/bug`) |
| `/release-notes` | View changelog |
| `/status` | Show version, model, account info |
## Keyboard Shortcuts {.cols-3}
### General Controls {.row-span-2}
| Shortcut | Description |
| ----------- | ---------------------------------- |
| `Ctrl+C` | Cancel current input or generation |
| `Ctrl+D` | Exit Claude Code |
| `Shift+Tab` | Cycle permission modes |
| `Ctrl+R` | Reverse search command history |
| `Ctrl+G` | Open prompt in text editor |
| `Ctrl+L` | Redraw the screen |
| `Ctrl+O` | Toggle verbose output |
| `Ctrl+V` | Paste image from clipboard |
| `Ctrl+B` | Background the running command |
| `Ctrl+T` | Toggle task list display |
| `Esc Esc` | Rewind or summarize conversation |
| `Option+P` | Switch model (macOS) |
| `Option+T` | Toggle extended thinking (macOS) |
| `Option+O` | Toggle fast mode (macOS) |
{.shortcuts}
### Text Editing
| Shortcut | Description |
| -------- | ----------------------- |
| `Ctrl+K` | Delete to end of line |
| `Ctrl+U` | Delete to start of line |
| `Ctrl+Y` | Paste deleted text |
| `Alt+Y` | Cycle paste history |
| `Alt+B` | Move back one word |
| `Alt+F` | Move forward one word |
{.shortcuts}
### Vim Mode
Enable with `/vim` or in `/config`. `Esc` → NORMAL, `i`/`a`/`o` → INSERT.
| Key | Action |
| --------------- | ----------------------------- |
| `h j k l` | Move left / down / up / right |
| `w` / `b` | Next / previous word |
| `0` / `$` | Line start / end |
| `gg` / `G` | Input start / end |
| `dd` / `yy` | Delete / yank line |
| `cc` / `p` | Change line / paste |
| `f{c}` / `F{c}` | Jump to character |
| `.` | Repeat last change |
### Multiline & Input
| Method | How |
| ------------------------- | ----------------------- |
| Multiline (all terminals) | `\` then `Enter` |
| Multiline (macOS default) | `Option+Enter` |
| Multiline (modern terms) | `Shift+Enter` |
| Run bash directly | `!` prefix |
| File path autocomplete | `@` prefix |
| All commands / skills | `/` prefix |
| Session picker shortcut | `P` preview, `R` rename |
macOS: set Option as Meta in terminal prefs for `Alt+*` shortcuts to work.
## Permission Modes {.cols-3}
### Modes Overview {.col-span-2 .row-span-2}
| Mode | What Claude does without asking | Best for |
| ------------------- | -------------------------------------- | ------------------------------------ |
| `default` | Read files only | Getting started, sensitive work |
| `acceptEdits` | Read + edit files | Active coding, iteration |
| `plan` | Read only, writes a plan file | Exploration, planning before editing |
| `auto` | All actions with background classifier | Long tasks, fewer interruptions |
| `dontAsk` | Only pre-approved tools | Locked CI/CD environments |
| `bypassPermissions` | All actions except protected dirs | Containers and VMs only |
{.show-header}
Regardless of mode, writes to `.git`, `.vscode`, `.idea`, `.husky`, and `.claude` always prompt (except `.claude/commands`, `.claude/agents`, `.claude/skills`).
#### Configure Default Mode
```json
{
"permissions": {
"defaultMode": "acceptEdits"
}
}
```
#### Auto Mode Notes
Requires Team / Enterprise / API plan + Claude Sonnet 4.6 or Opus 4.6. A separate classifier reviews each action before it runs and blocks actions that escalate beyond your intent. Enable at startup:
```bash
$ claude --enable-auto-mode
```
### Switch Modes
**During a session:**
Press `Shift+Tab` to cycle:
```
default → acceptEdits → plan → (auto)
```
**At startup:**
```bash
$ claude --permission-mode plan
$ claude --permission-mode acceptEdits
```
**Bypass all (containers only):** {.primary}
```bash
$ claude --dangerously-skip-permissions
```
### Permission Rules
Layer allow / deny rules on top of any mode in `.claude/settings.json`:
```json
{
"permissions": {
"allow": ["Bash(npm test)", "Bash(git log *)"],
"deny": ["Bash(rm -rf *)"]
}
}
```
View and edit rules with `/permissions`.
## Memory & CLAUDE.md {.cols-3}
### CLAUDE.md Locations {.col-span-2 .row-span-2}
| Scope | Location | Shared with |
| -------------- | ----------------------------------------- | ---------------------- |
| Managed policy | System-level (IT/DevOps deployed) | All users on machine |
| Project | `./CLAUDE.md` or `./.claude/CLAUDE.md` | Team via git |
| User | `~/.claude/CLAUDE.md` | Personal, all projects |
| Local | `./CLAUDE.local.md` (add to `.gitignore`) | Personal, this project |
{.show-header}
Files in parent directories load at launch. Subdirectory files load on demand when Claude reads files there. More specific scope wins on conflict.
#### Write Effective Instructions
- **Size**: keep each file under 200 lines — longer files reduce adherence
- **Specific**: `"Use 2-space indentation"` not `"format code nicely"`
- **Structured**: use markdown headers to group related rules
- **Consistent**: avoid conflicting instructions across files
Run `/init` to auto-generate a CLAUDE.md from your codebase. Set `CLAUDE_CODE_NEW_INIT=1` for an interactive multi-phase flow that also sets up skills and hooks.
#### Organize with `.claude/rules/`
```text
.claude/
├── CLAUDE.md
└── rules/
├── code-style.md # style guidelines
├── testing.md # test conventions
└── security.md # security requirements
```
#### Path-scoped Rules
```yaml
---
paths:
- 'src/api/**/*.ts'
- 'tests/**/*.test.ts'
---
# API Rules
All endpoints must include input validation.
```
Rules without `paths` load every session. Rules with `paths` load only when matching files are opened.
### Auto Memory
Claude saves its own notes in:
```
~/.claude/projects/<project>/memory/
├── MEMORY.md # index (first 200 lines loaded)
├── debugging.md # topic files (loaded on demand)
└── api-conventions.md
```
- On by default; toggle in `/memory` or set `autoMemoryEnabled: false`
- Persists across sessions and worktrees in the same git repo
- Machine-local — not shared across machines
Disable via env:
```bash
$ export CLAUDE_CODE_DISABLE_AUTO_MEMORY=1
```
### Import Syntax
Reference other files from CLAUDE.md:
```markdown
See @README.md for project overview.
Build commands: @package.json
# Workflows
@docs/git-workflow.md
```
- Both relative and absolute paths are supported
- Max import depth: 5 hops
- Imported files are expanded at session start
- HTML comments in CLAUDE.md are stripped from context
## Hooks {.cols-2}
### Hook Events {.row-span-2}
| Event | When it fires |
| -------------------- | ---------------------------------- |
| `SessionStart` | Session begins, resumes, or clears |
| `UserPromptSubmit` | User submits a prompt |
| `PreToolUse` | Before a tool executes |
| `PermissionRequest` | Before permission dialog shows |
| `PostToolUse` | After tool completes successfully |
| `PostToolUseFailure` | After tool execution fails |
| `PermissionDenied` | Auto mode classifier denies action |
| `Stop` | Claude finishes responding |
| `StopFailure` | Turn ends due to API error |
| `Notification` | Claude needs attention |
| `SubagentStart` | Subagent is spawned |
| `SubagentStop` | Subagent finishes |
| `FileChanged` | Watched file changes on disk |
| `PreCompact` | Before context compaction |
| `PostCompact` | After context compaction |
| `WorktreeCreate` | Worktree being created |
| `WorktreeRemove` | Worktree being removed |
| `InstructionsLoaded` | CLAUDE.md file loaded |
| `ConfigChange` | Settings file changes |
| `TaskCreated` | Task created via TaskCreate |
| `TaskCompleted` | Task marked complete |
{.show-header}
**Exit codes**: `0` = success (JSON decision), `2` = block action (stderr to model), other = non-blocking error.
Use `$CLAUDE_PROJECT_DIR` to reference hook scripts relative to the project root.
### Hook Types
| Type | Description |
| --------- | --------------------------------------- |
| `command` | Run shell script, reads JSON from stdin |
| `http` | POST JSON to an HTTP endpoint |
| `prompt` | Ask Claude for a yes/no decision |
| `agent` | Spawn subagent with tools to verify |
{.bold-first}
#### Auto-format After File Edits
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "npm run lint --silent"
}
]
}
]
}
}
```
#### Notify When Claude Needs You (macOS)
```json {.wrap}
{
"hooks": {
"Notification": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "osascript -e 'display notification \"Claude needs attention\" with title \"Claude Code\"'"
}
]
}
]
}
}
```
Config in `~/.claude/settings.json` (user) or `.claude/settings.json` (project). View hooks with `/hooks`.
## MCP Servers {.cols-2}
### Add MCP Server {.row-span-2}
#### Stdio server (local process)
```bash
$ claude mcp add my-server -- npx my-mcp-server
```
#### With environment variables
```bash
$ claude mcp add -e KEY=val my-server -- npx server
```
#### HTTP server
```bash {.wrap}
$ claude mcp add --transport http sentry https://mcp.sentry.dev/mcp
```
#### HTTP with auth header
```bash {.wrap}
$ claude mcp add --transport http my-api https://api.example.com/mcp --header "Authorization: Bearer $TOKEN"
```
#### JSON format
```bash
$ claude mcp add-json my-server '{"command":"npx","args":["my-mcp"]}'
```
#### Import from Claude Desktop
```bash
$ claude mcp add-from-claude-desktop
```
#### Manage servers
```bash
$ claude mcp list # list all servers
$ claude mcp get <name> # show server details
$ claude mcp remove <name> # remove a server
```
Config stored in `~/.claude/settings.json` (user) or `.claude/settings.json` (project).
### MCP in Session
**Reference MCP resources with `@`:**
```
@github:repos/owner/repo/issues
@memory:entities
@filesystem:/path/to/file
```
**Run MCP prompts as slash commands:**
```
/mcp__github__search_repositories
/mcp__memory__create_entities
```
MCP tool pattern: `mcp__<server>__<tool>`
**Manage in session:**
```
/mcp
```
**Hook on MCP tools:**
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "mcp__memory__.*",
"hooks": [{ "type": "command", "command": "logger.sh" }]
}
]
}
}
```
## Worktrees & Agents {.cols-2}
### Git Worktrees {.row-span-2}
Run parallel sessions in isolated branches:
```bash
# Create worktree and start Claude
$ claude --worktree feature-auth
$ claude -w bugfix-123
# Auto-generated name
$ claude --worktree
```
Worktrees are created at `.claude/worktrees/<name>/` and branch from `origin/HEAD`.
**Auto-cleanup:** no changes → removed on exit. With changes → Claude prompts to keep or remove.
Add to `.gitignore`:
```
.claude/worktrees/
```
#### Copy secrets to worktrees
Create `.worktreeinclude` in project root:
```
.env
.env.local
config/secrets.json
```
#### Manual worktree commands
```bash
# Create with specific branch
$ git worktree add ../project-feat -b feat
# List all worktrees
$ git worktree list
# Remove when done
$ git worktree remove ../project-feat
```
Re-sync origin HEAD after remote branch change:
```bash
$ git remote set-head origin -a
```
### Subagents
Create in `.claude/agents/<name>.md`:
```yaml
---
name: code-reviewer
description: Reviews code for bugs and style
tools:
- Read
- Grep
- Glob
---
You are an expert code reviewer.
Focus on correctness and clarity.
```
Use subagents naturally in conversation:
- `review the auth module for security issues`
- `use the code-reviewer agent on api.ts`
- `/agents` — manage agent configs
**Subagent with worktree isolation:**
```yaml
---
name: parallel-worker
isolation: worktree
description: Works in isolated branch
---
```
**Shared auto memory for subagents** — add to frontmatter:
```yaml
autoMemoryEnabled: true
```
## Headless & Scripting {.cols-2}
### Non-interactive Mode {.row-span-2}
Run Claude programmatically with `-p` / `--print`:
```bash
# Basic one-off query
$ claude -p "what does this file do?"
# Stream JSON (real-time events)
$ claude -p "query" --output-format stream-json
# JSON with full metadata
$ claude -p "query" --output-format json
# Limit turns and cost
$ claude -p "query" --max-turns 5 --max-budget-usd 1.00
# Validated structured output
$ claude -p "query" --json-schema '{"type":"object"}'
```
#### Resume in headless mode
```bash
# Continue most recent session
$ claude -c -p "follow-up question"
# Resume named session
$ claude -r my-session -p "continue the task"
```
#### Output formats
| Format | Use case |
| ------------- | ------------------------- |
| `text` | Human-readable (default) |
| `json` | Full metadata + cost info |
| `stream-json` | Real-time per-turn events |
{.bold-first}
#### Bare mode (faster startup)
```bash
$ claude --bare -p "query"
```
Skips hooks, CLAUDE.md auto-discovery, plugins, MCP, and auto memory. Sets `CLAUDE_CODE_SIMPLE=1`. Ideal for scripting.
#### Session persistence
```bash
# Don't save session to disk
$ claude -p "query" --no-session-persistence
```
### Scheduling
**Create a cloud scheduled task:**
```
/schedule review open PRs every morning at 9am
```
**Session-scoped loop (stays open):**
```
/loop 5m check for new issues
```
#### GitHub Actions
```yaml
- uses: anthropics/claude-code-action@beta
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
prompt: 'review this PR for issues and comment'
```
#### GitLab CI/CD
```yaml
claude-review:
script:
- claude -p "review changes in this MR"
--output-format json
```
| Scheduling option | Runs on |
| ----------------------- | ------------------------ |
| Cloud scheduled tasks | Anthropic infrastructure |
| Desktop scheduled tasks | Your local machine |
| GitHub Actions | CI/CD pipeline |
| `/loop` | Current CLI session only |
## Also see {.cols-1}
- [Claude Code Docs](https://code.claude.com/docs/en/overview) _(code.claude.com)_
- [CLI Reference](https://code.claude.com/docs/en/cli-reference) _(code.claude.com)_
- [All Slash Commands](https://code.claude.com/docs/en/commands) _(code.claude.com)_
- [Hooks Reference](https://code.claude.com/docs/en/hooks) _(code.claude.com)_
- [MCP Documentation](https://code.claude.com/docs/en/mcp) _(code.claude.com)_
- [Memory & CLAUDE.md](https://code.claude.com/docs/en/memory) _(code.claude.com)_
- [Permission Modes](https://code.claude.com/docs/en/permission-modes) _(code.claude.com)_
- [GitHub Repository](https://github.com/anthropics/claude-code) _(github.com)_
- [Community Discord](https://www.anthropic.com/discord) _(anthropic.com)_
+540
View File
@@ -0,0 +1,540 @@
---
title: Codex CLI
date: 2026-04-03 10:00:00
background: bg-[#10a37f]
tags:
- CLI
- AI
- OpenAI
- coding-agent
categories:
- AI
intro: |
OpenAI Codex CLI (v0.116+) is an open-source AI coding agent that reads, edits, and runs code directly in your terminal. See the [official docs](https://developers.openai.com/codex/cli) _(developers.openai.com)_.
plugins:
- copyCode
---
## Getting Started {.cols-2}
### Install & Run {.row-span-2}
#### npm (recommended)
```bash
$ npm install -g @openai/codex
$ npm install -g @openai/codex@latest # upgrade
```
#### Homebrew (macOS)
```bash
$ brew install codex
```
#### First run
```bash
$ codex # launch interactive TUI
$ codex "Explain this codebase" # with initial prompt
```
On first run you'll be prompted to sign in via ChatGPT or an API key.
#### Shell completions
```bash
# Zsh – add to ~/.zshrc
$ eval "$(codex completion zsh)"
# Bash – add to ~/.bashrc
$ eval "$(codex completion bash)"
# Fish
$ codex completion fish | source
```
### Platform Support
| Platform | Status |
| ---------------- | ------------ |
| macOS | Stable |
| Linux | Stable |
| Windows (WSL) | Recommended |
| Windows (native) | Experimental |
{.show-header}
### Authentication
```bash
$ codex login # ChatGPT OAuth
$ codex login --device-auth # device flow
# Pipe API key from env
$ printenv OPENAI_API_KEY | codex login --with-api-key
$ codex login status # check auth state
$ codex logout # remove credentials
```
## Subcommands {.cols-3}
### Command Reference {.col-span-2 .row-span-2}
| Command | Alias | Status | Description |
| ------------------ | --------- | ------------ | --------------------------------- |
| `codex` | | Stable | Launch interactive TUI |
| `codex exec` | `codex e` | Stable | Run non-interactively (scripting) |
| `codex review` | | Stable | Non-interactive code review |
| `codex resume` | | Stable | Resume a previous session |
| `codex fork` | | Stable | Fork a session into new thread |
| `codex apply` | `codex a` | Stable | Apply Cloud task diff locally |
| `codex login` | | Stable | Authenticate Codex |
| `codex logout` | | Stable | Remove stored credentials |
| `codex completion` | | Stable | Generate shell completions |
| `codex features` | | Stable | Manage feature flags |
| `codex app` | | Stable | Launch Codex desktop app |
| `codex mcp` | | Experimental | Manage MCP servers |
| `codex mcp-server` | | Experimental | Run Codex as an MCP server |
| `codex cloud` | | Experimental | Browse and exec Cloud tasks |
| `codex sandbox` | | Experimental | Run cmds inside sandbox |
| `codex debug` | | Experimental | Debugging tools |
{.show-header}
### Exec (Non-interactive)
```bash
# Basic non-interactive run
$ codex exec "Fix the race condition"
$ codex e "Add unit tests for utils"
# Prompt from stdin
$ echo "Explain main.go" | codex exec -
# Prompt-plus-stdin (0.118+): pipe data AND pass a prompt
$ cat error.log | codex exec "Diagnose this log" -
# Output options
$ codex exec --json "Audit security"
$ codex exec -o last.txt "Summarize"
# Resume a previous exec session
$ codex exec resume --last "Fix the bugs"
$ codex exec resume <SESSION_ID> "Implement"
```
## Global Options {.cols-2}
### All Flags {.row-span-3}
| Flag | Values | Description |
| ------------------------- | --------------- | ---------------------------------- |
| `-m, --model` | string | Model override (e.g. `gpt-5.4`) |
| `-s, --sandbox` | see below | Sandbox policy |
| `-a, --ask-for-approval` | see below | Approval policy |
| `--full-auto` | flag | workspace-write + on-request |
| `--yolo` | flag | Bypass all approvals/sandbox |
| `-i, --image` | path | Attach image(s) to initial prompt |
| `-c, --config` | `key=val` | Override a config value |
| `-C, --cd` | path | Agent working directory |
| `-p, --profile` | string | Config profile name |
| `--search` | flag | Enable live web search |
| `--add-dir` | path | Grant extra directory write access |
| `--oss` | flag | Use local OSS provider |
| `--local-provider` | lmstudio/ollama | Specify OSS provider |
| `--enable` | feature | Enable a feature flag |
| `--disable` | feature | Disable a feature flag |
| `--no-alt-screen` | flag | Inline TUI mode (no alt screen) |
| `--remote` | ws://host:port | Connect to remote app server |
| `--remote-auth-token-env` | ENV_VAR | Bearer token env var for remote WS |
| `-V, --version` | | Print version |
| `-h, --help` | | Print help |
{.show-header}
### Usage Examples
```bash {.wrap}
# Specify model
$ codex -m gpt-5.4 "Refactor the auth module"
# Auto mode (low friction)
$ codex --full-auto "Run tests and fix failures"
# Attach a screenshot
$ codex -i mockup.png "Implement this UI"
# Override config inline
$ codex -c model="gpt-5.4-mini" "Quick scan"
# Live web search
$ codex --search "Find the latest async syntax"
# Set working directory
$ codex -C ~/projects/api "Review this codebase"
```
## Sandbox & Approvals {.cols-3}
### Sandbox Modes
| Mode | Description |
| -------------------- | --------------------------------------- |
| `read-only` | Inspect only, no edits without approval |
| `workspace-write` | Edit workspace + run local commands |
| `danger-full-access` | No restrictions (use in hardened envs) |
### Approval Policies
| Policy | Description |
| ------------ | ----------------------------------------- |
| `untrusted` | Ask before all non-trusted commands |
| `on-request` | Ask when going beyond sandbox boundary |
| `never` | Never ask; all commands run automatically |
### Presets {.primary}
| Preset | Equivalent setting |
| ------------- | -------------------------------- |
| `--full-auto` | `workspace-write` + `on-request` |
| `--yolo` | No sandbox + No approvals |
Use `/permissions` in the TUI to change modes mid-session.
## Slash Commands {.cols-3}
### Session Control {.row-span-2}
| Command | Description |
| ----------------- | ------------------------------- |
| `/model` | Switch model / reasoning effort |
| `/fast` | Toggle GPT-5.4 Fast mode |
| `/permissions` | Adjust approval mode |
| `/personality` | Set response style |
| `/plan` | Enter planning mode |
| `/status` | Show model, tokens, config |
| `/compact` | Summarize to free context |
| `/clear` | Clear chat + start fresh |
| `/new` | New chat, keep CLI session |
| `/fork` | Fork current conversation |
| `/resume` | Resume saved session |
| `/exit` / `/quit` | Exit the CLI |
### Review & Code
| Command | Description |
| ---------- | --------------------------- |
| `/review` | Launch code reviewer |
| `/diff` | Show Git diff |
| `/copy` | Copy latest Codex output |
| `/mention` | Attach file to conversation |
| `/init` | Generate AGENTS.md scaffold |
### Tools & Debug
| Command | Description |
| ----------------------- | ------------------------------ |
| `/agent` | Switch active agent thread |
| `/mcp` | List MCP tools |
| `/apps` | Browse connector apps |
| `/experimental` | Toggle experimental features |
| `/statusline` | Configure TUI footer |
| `/ps` | Show background terminals |
| `/sandbox-add-read-dir` | Add readable dir (Windows) |
| `/feedback` | Send logs to maintainers |
| `/plugins` | Browse and manage plugins |
| `/title` | Set terminal title for session |
| `/debug-config` | Print config diagnostics |
| `/logout` | Sign out of Codex |
## Models {.cols-3}
### Available Models {.col-span-2}
| Model | Speed | Best for |
| --------------------- | ----- | ---------------------------------------- |
| `gpt-5.4` | ★★★ | Default – coding + reasoning + workflows |
| `gpt-5.4-mini` | ★★★★★ | Subagents, light tasks, higher limits |
| `gpt-5.3-codex` | ★★★★ | Complex software engineering |
| `gpt-5.3-codex-spark` | ★★★★★ | Near-instant iteration (Pro only) |
{.show-header}
### Select a Model
```bash
$ codex -m gpt-5.4 "Your prompt"
$ codex -m gpt-5.4-mini "Quick task"
$ codex --oss # local Ollama / LM Studio
# Mid-session: type /model in the TUI
```
## Configuration {.cols-2}
### config.toml Keys {.row-span-2}
```toml
# ~/.codex/config.toml
# Model settings
model = "gpt-5.4"
model_provider = "openai"
model_reasoning_effort = "medium" # low | medium | high
# Sandbox & approvals
sandbox_mode = "workspace-write"
approval_policy = "on-request"
# Web search: cached | live | disabled
web_search = "cached"
# Review model override
review_model = "gpt-5.4"
# TUI appearance
[tui]
theme = "dark"
alternate_screen = true
# Profile example
[profile.ci]
model = "gpt-5.4-mini"
approval_policy = "never"
sandbox_mode = "workspace-write"
```
Use `-p ci` to activate a profile.
### Feature Flags
```bash
$ codex features list
$ codex features enable unified_exec
$ codex features disable shell_snapshot
# Per-session (not persisted)
$ codex --enable unified_exec
$ codex --disable shell_snapshot
```
### Config Locations
| File | Purpose |
| ---------------------- | --------------------- |
| `~/.codex/config.toml` | Global defaults |
| `~/.codex/AGENTS.md` | Personal instructions |
| `~/.agents/skills/` | Personal skills |
| `.agents/skills/` | Repo-level skills |
| `AGENTS.md` | Repo instructions |
## Customization {.cols-3}
### AGENTS.md {.row-span-2}
Persistent repo instructions, checked in alongside code:
```markdown
## Build & test commands
- Install: `npm install`
- Test: `npm test`
- Lint: `npm run lint`
## Conventions
- TypeScript strict mode
- No PII in logs
- Auth middleware on all routes
## Review guidelines
- Flag unhandled promise rejections
```
When to add rules:
- Repeated agent mistakes
- Recurring PR review feedback
- Tag `@codex add to AGENTS.md` in GitHub
### Skills
Reusable workflows packaged as `SKILL.md`:
```
my-skill/
SKILL.md ← metadata + instructions
scripts/ ← optional helper scripts
references/ ← optional documentation
assets/ ← optional templates
```
Example `SKILL.md`:
```markdown
---
name: commit
description: Stage and commit changes
in semantic groups.
---
1. Stage files in logical groups.
2. Group: feat → test → docs → chore
3. Write concise commit messages.
```
### MCP Servers
```bash
# Add a stdio server
$ codex mcp add myserver -- npx my-mcp-server
# Add an HTTP server
$ codex mcp add myserver \
--url https://api.example.com/mcp
# With auth token
$ codex mcp add myserver \
--url https://api.example.com/mcp \
--bearer-token-env-var MY_TOKEN
# List / remove
$ codex mcp list
$ codex mcp remove myserver
# Run Codex itself as MCP server
$ codex mcp-server
```
## Session Management {.cols-3}
### Resume Sessions
```bash
$ codex resume # session picker
$ codex resume --last # most recent session
$ codex resume --all # across all directories
$ codex resume <ID> "Continue fixing tests"
```
Sessions stored at `~/.codex/sessions/`
### Fork a Session
```bash
$ codex fork # fork from picker
$ codex fork --last # fork most recent
$ codex fork <SESSION_ID> "New direction"
```
Forking preserves the original transcript while starting a new branch.
### Image Inputs
```bash
# Single image
$ codex -i screenshot.png "Fix this error"
# Multiple images
$ codex --image img1.png,img2.jpg "Compare"
# Or drag images into the TUI composer
```
Supported: PNG, JPEG and other common formats.
## Cloud & GitHub {.cols-3}
### Cloud Tasks {.col-span-2}
```bash
# Browse cloud environments
$ codex cloud
# Submit a cloud task
$ codex cloud exec --env <ENV_ID> "Fix bug"
# With multiple attempts (best-of-N)
$ codex cloud exec --env <ENV_ID> \
--attempts 3 "Write failing tests"
# List recent tasks
$ codex cloud list
# Check task status
$ codex cloud status <TASK_ID>
# Show diff for a task
$ codex cloud diff <TASK_ID>
# Apply diff to local working tree
$ codex apply <TASK_ID>
```
### GitHub Integration
```
# In a PR comment – trigger code review:
@codex review
# Custom focus:
@codex review for security regressions
# Delegate any task using PR as context:
@codex fix the CI failures
@codex add tests for the new endpoint
```
Enable in Codex Settings → Code review → your repo. Turn on Automatic reviews to review every new PR.
## Subagent Workflows {.cols-2}
### Subagents Guide {.row-span-2}
Offload noisy work to parallel agents to avoid **context pollution** and **context rot**:
```
codex "Review this branch with parallel agents.
Spawn one for security risks, one for test gaps,
and one for maintainability. Wait for all three,
then summarize findings with file references."
```
- Use for: exploration, tests, triage, log analysis
- Avoid parallel write-heavy work (conflicts)
- Each subagent consumes extra tokens
**Subagent model guide:**
| Role | Model | Reasoning |
| ----------------------- | -------------- | --------- |
| Main coordinator | `gpt-5.4` | medium |
| Fast exploration | `gpt-5.4-mini` | low |
| Security / logic review | `gpt-5.4` | high |
{.show-header}
### Reasoning Effort
| Level | Use when |
| -------- | ------------------------------ |
| `high` | Complex logic, security audits |
| `medium` | General tasks (default) |
| `low` | Simple or speed-critical tasks |
Set in `config.toml`:
```toml
model_reasoning_effort = "medium"
```
Or inline: `-c model_reasoning_effort="high"`
## Also See {.cols-1}
- [Official Codex Docs](https://developers.openai.com/codex/cli) _(developers.openai.com)_
- [Codex CLI GitHub](https://github.com/openai/codex) _(github.com)_
- [Codex Pricing](https://developers.openai.com/codex/pricing) _(developers.openai.com)_
- [Customization Guide](https://developers.openai.com/codex/concepts/customization) _(developers.openai.com)_
- [Prompting Best Practices](https://developers.openai.com/codex/prompting) _(developers.openai.com)_
- [Workflows & Examples](https://developers.openai.com/codex/workflows) _(developers.openai.com)_
+795
View File
@@ -0,0 +1,795 @@
---
title: Gemini CLI
date: 2026-04-03 12:00:00
background: bg-[#1a73e8]
tags:
- gemini
- ai
- cli
- google
categories:
- AI
intro: |
[Gemini CLI](https://geminicli.com/docs/) brings Google Gemini models directly into your terminal for code understanding, task automation, and workflow building.
plugins:
- copyCode
---
## Getting Started {.cols-3}
### Quick Start {.row-span-2}
```bash
# Install globally
$ npm install -g @google/gemini-cli
# Or via Homebrew
$ brew install gemini-cli
# Or run without installing
$ npx @google/gemini-cli
# Launch interactive session
$ gemini
# Non-interactive (headless)
$ gemini -p "summarize README.md"
# Pipe content to Gemini
$ cat logs.txt | gemini -p "find errors"
# Run prompt and continue interactively
$ gemini -i "explain this project"
# Resume most recent session
$ gemini -r latest
# Resume with new prompt
$ gemini -r latest "check for type errors"
```
### Authentication
| Method | How |
| --------------- | ------------------------------------------ |
| Google Account | Run `gemini`, select "Sign in with Google" |
| API Key | Set `GEMINI_API_KEY` env var |
| Vertex AI (ADC) | `gcloud auth application-default login` |
| Vertex AI (SA) | Set `GOOGLE_APPLICATION_CREDENTIALS` |
Vertex AI also requires `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION`.
### Installation Methods
| Method | Command |
| ---------------- | ----------------------------------- |
| npm | `npm install -g @google/gemini-cli` |
| Homebrew | `brew install gemini-cli` |
| MacPorts | `sudo port install gemini-cli` |
| npx (no install) | `npx @google/gemini-cli` |
**System requirements:** Node.js 20+, macOS 15+, Windows 11 24H2+, or Ubuntu 20.04+
### Model Aliases
| Alias | Model | Use For |
| ------------ | ----------------------------- | ----------------- |
| `auto` | gemini-2.5-pro / gemini-3-pro | Default, balanced |
| `pro` | gemini-2.5-pro / gemini-3-pro | Complex reasoning |
| `flash` | gemini-2.5-flash | Fast, balanced |
| `flash-lite` | gemini-2.5-flash-lite | Simple, fastest |
{.show-header}
Set with `-m flash` or `GEMINI_MODEL` env var.
### Key Concepts
| Concept | Description |
| ----------- | ----------------------------------------------- |
| `GEMINI.md` | Project context file loaded automatically |
| Skills | On-demand expertise loaded via `activate_skill` |
| Extensions | Bundles of prompts, MCP servers, tools |
| MCP Servers | External tools via Model Context Protocol |
| Plan Mode | Read-only mode for planning before coding |
| Hooks | Scripts that run at key agent lifecycle points |
| Headless | Non-interactive mode via `-p` flag |
| Sessions | Saved conversation history, resumable |
## CLI Options {.cols-2}
### Core Options {.row-span-2}
| Option | Alias | Description |
| ---------------------------- | ----- | --------------------------------------------------------- |
| `--prompt <text>` | `-p` | Non-interactive prompt |
| `--prompt-interactive` | `-i` | Prompt then continue |
| `--model <name>` | `-m` | Model to use |
| `--worktree [name]` | `-w` | Start in new git worktree |
| `--sandbox` | `-s` | Enable sandboxed execution |
| `--approval-mode <mode>` | | default / auto_edit / yolo / plan |
| `--yolo` | `-y` | Auto-approve all (deprecated, use `--approval-mode=yolo`) |
| `--resume <id>` | `-r` | Resume session by ID or `latest` |
| `--list-sessions` | | List sessions and exit |
| `--delete-session <n>` | | Delete session by index |
| `--output-format <fmt>` | `-o` | text / json / stream-json |
| `--extensions <list>` | `-e` | Extensions to load |
| `--list-extensions` | `-l` | List extensions and exit |
| `--include-directories` | | Additional workspace dirs |
| `--allowed-mcp-server-names` | | Restrict MCP server names |
| `--screen-reader` | | Enable accessibility mode |
| `--acp` | | Start in ACP (Agent Code Pilot) mode |
| `--debug` | `-d` | Verbose debug logging |
| `--version` | `-v` | Show version |
| `--help` | `-h` | Show help |
### Subcommands
```bash
# MCP server management
$ gemini mcp add <name> <cmd-or-url>
$ gemini mcp remove <name>
$ gemini mcp list
$ gemini mcp enable <name>
$ gemini mcp disable <name>
# Extension management
$ gemini extensions install <source>
$ gemini extensions uninstall <name>
$ gemini extensions list
$ gemini extensions update [name] [--all]
$ gemini extensions enable/disable <name>
$ gemini extensions link <path>
$ gemini extensions new <path>
# Skills management
$ gemini skills list [--all]
$ gemini skills install <source>
$ gemini skills link <path>
$ gemini skills uninstall <name>
$ gemini skills enable/disable <name>
# Hooks
$ gemini hooks migrate
```
### Headless Output Formats
| Format | Description |
| ------------- | --------------------------------------------------------------------------- |
| `text` | Plain text (default) |
| `json` | Single JSON object with `response` and `stats` |
| `stream-json` | JSONL: `init` · `message` · `tool_use` · `tool_result` · `error` · `result` |
**Exit codes:** `0` Success · `1` Error · `42` Bad input · `53` Turn limit exceeded
## Interactive Commands {.cols-3}
### Slash Commands `/` {.row-span-3}
| Command | Description |
| -------------------- | ------------------------------- |
| `/help` | Show all commands |
| `/quit` `/exit` | Exit Gemini CLI |
| `/clear` | Clear terminal screen |
| `/about` | Show version info |
| `/auth` | Change authentication |
| `/model` | Set / manage model |
| `/settings` | Open settings editor |
| `/theme` | Change visual theme |
| `/vim` | Toggle vim mode |
| `/plan [goal]` | Enter Plan Mode |
| `/compress` | Compress chat context |
| `/copy` | Copy last output to clipboard |
| `/init` | Generate GEMINI.md for project |
| `/docs` | Open documentation |
| `/bug` | File a GitHub issue |
| `/stats` | Session / model / tools stats |
| `/tools` | List available tools |
| `/memory show` | Show all context files |
| `/memory add <text>` | Add to global GEMINI.md |
| `/memory reload` | Reload context files |
| `/resume` | Browse & resume sessions |
| `/rewind` | Rewind conversation history |
| `/restore` | Restore pre-tool file state |
| `/hooks list` | List configured hooks |
| `/mcp list` | List MCP servers |
| `/mcp reload` | Restart MCP servers |
| `/skills list` | List available skills |
| `/extensions list` | List extensions |
| `/permissions trust` | Trust current folder |
| `/policies list` | List active policies |
| `/directory add` | Add workspace directory |
| `/ide status` | IDE integration status |
| `/shells` | Toggle background shells |
| `/terminal-setup` | Configure multiline keybindings |
| `/setup-github` | Setup GitHub Actions |
Reload commands: `/skills reload`, `/agents reload`, `/commands reload`, `/memory reload`, `/mcp reload`, `/extensions reload`
### At Commands `@`
Include file or directory content in your prompt:
```bash
# Include a file
@src/main.ts fix the bug on line 42
# Include a directory
@src/ what does this module do?
# Include multiple paths
@package.json @src/ audit dependencies
```
Git-aware: respects `.gitignore` for directory inclusion.
### Shell Mode `!`
```bash
# Run a single shell command
!ls -la
# Toggle persistent shell mode
!
# Shell output injected into context
!git diff HEAD~1
```
`GEMINI_CLI=1` is set in all shell subprocesses.
## Keyboard Shortcuts {.cols-3}
### Cursor & Editing {.row-span-2}
| Key | Action |
| --------------------- | ----------------------- |
| `Ctrl+A` / `Home` | Move to line start |
| `Ctrl+E` / `End` | Move to line end |
| `Ctrl+←` / `Alt+B` | Move word left |
| `Ctrl+→` / `Alt+F` | Move word right |
| `Ctrl+K` | Delete to end of line |
| `Ctrl+U` | Delete to start of line |
| `Ctrl+W` / `Alt+Bksp` | Delete word left |
| `Alt+D` | Delete word right |
| `Backspace` | Delete left |
| `Delete` / `Ctrl+D` | Delete right |
| `Cmd+Z` | Undo |
| `Ctrl+Shift+Z` | Redo |
{.shortcuts}
### Text Input
| Key | Action |
| ---------------- | ---------------------- |
| `Enter` | Submit message |
| `Ctrl/Cmd+Enter` | Insert newline |
| `Tab` | Queue message |
| `Ctrl+X` | Open external editor |
| `Ctrl+V` | Paste |
| `Ctrl+R` | Reverse history search |
| `Ctrl+P` | Previous history entry |
| `Ctrl+N` | Next history entry |
{.shortcuts}
### App Controls
| Key | Action |
| ----------- | ------------------------- |
| `Shift+Tab` | Cycle approval modes |
| `Ctrl+T` | Toggle todos panel |
| `Alt+M` | Toggle markdown rendering |
| `Ctrl+Y` | Toggle YOLO mode |
| `Ctrl+L` | Clear screen |
| `Ctrl+Z` | Suspend process |
| `F12` | Show error details |
| `Esc` twice | Open rewind dialog |
| `Ctrl+C` | Cancel / quit |
| `Ctrl+D` | Exit |
{.shortcuts}
## Sessions & History {.cols-3}
### Session Management {.row-span-2}
```bash
# List all sessions
$ gemini --list-sessions
# Resume most recent
$ gemini -r latest
# Resume specific session
$ gemini -r <session-id>
# Delete by index
$ gemini --delete-session 3
```
**Inside the `/resume` browser:**
- `↑↓` to navigate sessions
- `Enter` to resume selected session
- `x` to delete a session
- Search by typing
### Rewind Workflow
`/rewind` or press `Esc` twice to open the rewind dialog:
| Option | Effect |
| --------------- | ----------------------------------- |
| Rewind + Revert | Reset chat history AND file changes |
| Rewind only | Reset chat history, keep files |
| Revert only | Restore files, keep chat history |
| Do nothing | Cancel (Esc) |
Applies only to AI-made file changes, not manual edits or `!` shell commands.
### Fork a Conversation
Save and restore named checkpoints to explore multiple approaches:
```bash
# 1. Save current state
/resume save my-decision-point
# 2. Try approach A...
# 3. Restore to saved state
/resume resume my-decision-point
# 4. Try approach B...
```
## Context & Memory {.cols-3}
### GEMINI.md Hierarchy {.row-span-2}
Context files are loaded in this order (all merged):
| Priority | Location |
| ------------------ | ------------------------------ |
| 1. Global | `~/.gemini/GEMINI.md` |
| 2. Parent dirs | Scanned up from workspace |
| 3. Workspace | `.gemini/GEMINI.md` |
| 4. JIT (on-demand) | Scanned when tools access dirs |
```markdown
# Importing other files inside GEMINI.md
@./docs/architecture.md
@./docs/conventions.md
```
Customize the filename via `context.fileName` in `settings.json` (can be an array: `["AGENTS.md", "GEMINI.md"]`).
### Memory Commands
```bash
# Show all loaded context
/memory show
# Force reload all context files
/memory reload
# Append text to global GEMINI.md
/memory add "Always use TypeScript strict mode"
# Generate project GEMINI.md
/init
```
### Ignoring Files
Create `.geminiignore` in project root (follows `.gitignore` syntax):
```gitignore
# Exclude a directory
/packages/
# Exclude specific files
apikeys.txt
*.log
# Exclude all .md except README
*.md
!README.md
```
Files are hidden from CLI tools but remain visible to Git and other services.
## MCP Servers {.cols-2}
### MCP Config {.row-span-2}
```json
{
"mcpServers": {
"my-server": {
"command": "npx",
"args": ["-y", "my-mcp-package"],
"env": { "API_KEY": "$MY_API_KEY" },
"timeout": 30000,
"trust": false,
"includeTools": ["tool1", "tool2"],
"excludeTools": ["dangerous-tool"]
},
"remote-server": {
"url": "https://api.example.com/mcp",
"headers": { "Authorization": "Bearer $TOKEN" }
}
}
}
```
Env vars support `$VAR`, `${VAR}`, and `%VAR%` (Windows) expansion.
Tool FQN pattern: `mcp_{serverName}_{toolName}`
### Managing Servers
```bash {.wrap}
# Add stdio server
$ gemini mcp add myserver npx -y my-mcp-package
# Add HTTP server
$ gemini mcp add myserver https://api.example.com/mcp
# Add with options
$ gemini mcp add myserver cmd --transport http --trust --timeout 30000
# List all servers
$ gemini mcp list
# Remove a server
$ gemini mcp remove myserver
# Enable / disable
$ gemini mcp enable myserver
$ gemini mcp disable myserver --session
```
### MCP Server Config Fields
| Field | Description |
| -------------- | --------------------------------------- |
| `command` | Executable for stdio transport |
| `args` | Arguments array |
| `url` | URL for SSE transport |
| `httpUrl` | URL for Streamable HTTP |
| `env` | Environment variables |
| `cwd` | Working directory |
| `timeout` | Connection timeout (ms, default 600000) |
| `trust` | Skip confirmation for all tools |
| `includeTools` | Whitelist specific tools |
| `excludeTools` | Blacklist specific tools |
### MCP Resources
Reference MCP resources in prompts:
```bash
# Reference a resource
@server://resource/path summarize this
# Slash commands from MCP prompts
/prompt-name --arg=value
```
## Extensions & Skills {.cols-3}
### Managing Extensions {.row-span-2}
```bash
# Install from GitHub
$ gemini extensions install https://github.com/org/ext
# Install from local path
$ gemini extensions install ./my-extension
# List installed
$ gemini extensions list
# Update all
$ gemini extensions update --all
# Update specific
$ gemini extensions update my-ext
# Enable / disable
$ gemini extensions enable my-ext
$ gemini extensions disable my-ext --scope user
# Link for development
$ gemini extensions link ./dev-extension
# Create new extension
$ gemini extensions new ./my-new-ext
# Validate structure
$ gemini extensions validate ./my-ext
```
Extensions bundle: prompts, MCP servers, custom commands, themes, hooks, subagents, and skills.
### Agent Skills
Skills provide on-demand expertise — loaded only when `activate_skill` is called.
**Discovery locations (precedence):**
| Tier | Path |
| --------- | ------------------------------------------ |
| Workspace | `.gemini/skills/` or `.agents/skills/` |
| User | `~/.gemini/skills/` or `~/.agents/skills/` |
| Extension | Bundled within extension |
```bash
# List all skills
$ gemini skills list --all
# Install from Git or local
$ gemini skills install https://github.com/org/skill
$ gemini skills install ./local-skill
# Link for development
$ gemini skills link ./my-skill
# Enable / disable
$ gemini skills enable my-skill
$ gemini skills disable my-skill
```
### Custom Commands
Save reusable prompts as slash commands.
**File locations:**
- User: `~/.gemini/commands/`
- Project: `.gemini/commands/`
```toml
# .gemini/commands/git/commit.toml
description = "Generate commit message"
prompt = """
Generate a conventional commit message for:
!{git diff --staged}
{{args}}
"""
```
Command becomes `/git:commit`. Subdirectory `/` → `:` namespace.
**Placeholders:**
| Placeholder | Meaning |
|---|---|
| `{{args}}` | Inject user arguments |
| `!{cmd}` | Execute shell, inject output |
| `@{path}` | Embed file content |
## Plan Mode {.cols-3}
### Enabling Plan Mode {.row-span-2}
```bash
# One-time via flag
$ gemini --approval-mode=plan
# Natural language trigger
> let's plan the refactor first
# Slash command
/plan redesign the auth module
# Cycle modes with Shift+Tab during session
```
Set as default in `settings.json`:
```json
{
"general": {
"defaultApprovalMode": "plan"
}
}
```
### Plan Mode Tools
**Read-only (always available):**
- `read_file`, `list_directory`, `glob`
- `grep_search`, `google_web_search`
- `web_fetch` (with confirmation)
- `codebase_investigator`, `cli_help`
- `ask_user`
**Write (restricted):**
- `write_file`, `replace` — only for `.md` files inside plans directory
**Memory:**
- `save_memory`, `activate_skill`
### Plan Mode Workflow
```
1. Set goal
└─ natural language or /plan <goal>
2. Discuss strategy
└─ Gemini may ask clarifying questions
3. Review plan
└─ Markdown file written to plans dir
└─ Ctrl+X to edit in external editor
4. Approve or iterate
5. Switch to YOLO/auto_edit to implement
```
Auto model routing: Pro during planning → Flash during implementation.
## Configuration {.cols-2}
### Settings File Locations {.row-span-2}
| Scope | Path |
| ---------------- | ----------------------------------------- |
| User | `~/.gemini/settings.json` |
| Project | `.gemini/settings.json` |
| System (Linux) | `/etc/gemini-cli/settings.json` |
| System (macOS) | `/Library/Application Support/GeminiCli/` |
| System (Windows) | `C:\ProgramData\gemini-cli\settings.json` |
{.no-wrap}
**Precedence (highest wins):**
CLI args → env vars → system settings → project settings → user settings → system defaults
**Common settings:**
```json
{
"general": {
"defaultApprovalMode": "default",
"checkpointing": { "enabled": true }
},
"ui": {
"theme": "dark"
},
"model": {
"name": "auto"
},
"tools": {
"sandbox": "docker"
}
}
```
Open the visual editor with `/settings`.
### Key Environment Variables
| Variable | Purpose |
| -------------------------------- | ------------------------------------------------- |
| `GEMINI_API_KEY` | Gemini API authentication |
| `GEMINI_MODEL` | Default model override |
| `GEMINI_CLI_HOME` | Override config directory |
| `GOOGLE_CLOUD_PROJECT` | Vertex AI project |
| `GOOGLE_CLOUD_LOCATION` | Vertex AI region |
| `GOOGLE_APPLICATION_CREDENTIALS` | Service account JSON path |
| `GOOGLE_API_KEY` | Google Cloud API key |
| `GEMINI_SANDBOX` | Sandbox type: `true`, `docker`, `podman`, `runsc` |
| `GEMINI_SYSTEM_MD` | Path to system prompt file |
| `NO_COLOR` | Disable colored output |
| `CLI_TITLE` | Override terminal window title |
Persist in `~/.bashrc`, `~/.zshrc`, or `.gemini/.env`.
### Sandboxing Options
| Method | Platform | How to Enable |
| --------------- | ------------------ | -------------------------------------- |
| macOS Seatbelt | macOS only | `GEMINI_SANDBOX=sandbox-exec` |
| Docker/Podman | Cross-platform | `--sandbox` or `GEMINI_SANDBOX=docker` |
| gVisor (runsc) | Linux only | `GEMINI_SANDBOX=runsc` |
| LXC/LXD | Linux experimental | `GEMINI_SANDBOX=lxc` |
| Windows Sandbox | Windows only | `GEMINI_SANDBOX=true` |
{.show-header}
## Hooks {.cols-2}
### Hook Events {.row-span-3}
| Event | When | Can Block? |
| --------------------- | ---------------------- | ----------------- |
| `SessionStart` | Session begins | No (advisory) |
| `SessionEnd` | Session ends | No (best effort) |
| `BeforeAgent` | Before planning starts | Yes (exit 2) |
| `AfterAgent` | Agent loop ends | Yes (force retry) |
| `BeforeModel` | Before LLM call | Yes (exit 2) |
| `AfterModel` | After each LLM chunk | Yes (exit 2) |
| `BeforeToolSelection` | Before tool choice | Filter tools |
| `BeforeTool` | Before tool runs | Yes (exit 2) |
| `AfterTool` | After tool runs | Yes (hide result) |
| `PreCompress` | Before compression | No (advisory) |
| `Notification` | System notifications | No |
**Exit codes:** `0` = success · `2` = block/critical · other = warning
**Hook config in `settings.json`:**
```json
{
"hooks": {
"BeforeTool": [
{
"type": "command",
"command": "~/.gemini/hooks/validate-tool.sh",
"matcher": "write_file",
"timeout": 10000
}
],
"SessionStart": [
{
"type": "command",
"command": "echo '{\"systemMessage\": \"Be concise.\"}'"
}
]
}
}
```
### Hook I/O Protocol
All hooks receive JSON via **stdin**:
```json
{
"session_id": "...",
"transcript_path": "/path/to/transcript",
"cwd": "/project/dir",
"hook_event_name": "BeforeTool",
"timestamp": "2026-01-01T00:00:00Z"
}
```
Respond with JSON on **stdout**:
| Field | Description |
| ---------------- | ----------------------- |
| `decision` | `"allow"` or `"deny"` |
| `reason` | Shown to user on denial |
| `systemMessage` | Injected into context |
| `suppressOutput` | Hide hook output |
| `continue` | `false` to halt agent |
**BeforeTool** extra: `hookSpecificOutput.tool_input` overrides args.
**AfterTool** extra: `hookSpecificOutput.additionalContext` appended to result.
**BeforeAgent** extra: `hookSpecificOutput.additionalContext` appended to prompt.
**Environment vars available:**
`GEMINI_PROJECT_DIR`, `GEMINI_SESSION_ID`, `GEMINI_CWD`
## Also see {.cols-1}
- [Official Documentation](https://geminicli.com/docs/) _(geminicli.com)_
- [CLI Cheatsheet](https://geminicli.com/docs/cli/cli-reference) _(geminicli.com)_
- [Keyboard Shortcuts Reference](https://geminicli.com/docs/reference/keyboard-shortcuts) _(geminicli.com)_
- [Configuration Reference](https://geminicli.com/docs/reference/configuration) _(geminicli.com)_
- [Hooks Reference](https://geminicli.com/docs/hooks/reference) _(geminicli.com)_
- [GitHub Repository](https://github.com/google-gemini/gemini-cli) _(github.com)_
+579
View File
@@ -0,0 +1,579 @@
---
title: Gemma 4
date: 2026-04-03 10:00:00
background: bg-[#4285f4]
tags:
- gemma
- google
- llm
- multimodal
- ai
categories:
- Other
intro: |
[Gemma 4](https://deepmind.google/models/gemma/gemma-4/) is Google DeepMind's Apache 2.0 open-weights multimodal LLM family with frontier intelligence across four sizes, from mobile-edge to server-grade deployment.
plugins:
- copyCode
---
## Getting Started
### Quick Start {.row-span-2}
```python
from transformers import AutoProcessor, AutoModelForCausalLM
import torch
MODEL_ID = "google/gemma-4-E4B-it"
processor = AutoProcessor.from_pretrained(MODEL_ID)
model = AutoModelForCausalLM.from_pretrained(
MODEL_ID,
dtype=torch.bfloat16,
device_map="auto"
)
messages = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Explain MoE briefly."},
]
text = processor.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=False
)
inputs = processor(
text=text, return_tensors="pt"
).to(model.device)
input_len = inputs["input_ids"].shape[-1]
outputs = model.generate(**inputs, max_new_tokens=512)
response = processor.decode(
outputs[0][input_len:], skip_special_tokens=False
)
result = processor.parse_response(response)
# result["thinking"] → internal reasoning chain
# result["response"] → final answer shown to user
```
### Introduction
- [Docs](https://ai.google.dev/gemma/docs/core) _(ai.google.dev)_
- [Model Card](https://ai.google.dev/gemma/docs/core/model_card_4) _(ai.google.dev)_
- [HuggingFace](https://huggingface.co/google) _(huggingface.co)_
- [Cookbook](https://github.com/google-gemma/gemma-cookbook) _(github.com)_
Released 2026-03-31 · Apache 2.0 · Built from Gemini 3 research · 140+ languages
### Install
```bash
$ pip install -U transformers torch accelerate
```
All models: `google/<model-id>` on HuggingFace
| Size | Model ID |
| ------- | -------------------- |
| E2B | `gemma-4-E2B-it` |
| E4B | `gemma-4-E4B-it` |
| 31B | `gemma-4-31b-it` |
| 26B A4B | `gemma-4-26b-a4b-it` |
### Sampling Params
| Parameter | Value |
| ------------- | ------ |
| `temperature` | `1.0` |
| `top_p` | `0.95` |
| `top_k` | `64` |
{.bold-first}
### Best Practices
- Place images/audio **before** text in any prompt
- Multi-turn: omit thought blocks from conversation history
- Include 75%+ CoT data to preserve reasoning capability
- Freeze vision layers when text-only fine-tuning
## Model Family {.cols-2}
### Model Specs {.col-span-2}
| Model | Arch | Total Params | Active/Token | Layers | Context | Modalities |
| ------- | --------- | --------------- | ------------ | ------ | ------- | ---------------- |
| E2B | Dense+PLE | 5.1B (2.3B eff) | 2.3B | 35 | 128K | Text+Image+Audio |
| E4B | Dense+PLE | 8B (4.5B eff) | 4.5B | 42 | 128K | Text+Image+Audio |
| 31B | Dense | 30.7B | 30.7B | 60 | 256K | Text+Image |
| 26B A4B | MoE | 25.2B | 3.8B | 30 | 256K | Text+Image |
{.show-header}
Sliding window: 512 tokens (E2B/E4B) · 1024 tokens (31B/26B) · Vocab: 262K (all models)
### Architecture Features {.row-span-2}
#### Hybrid Attention
- **Local** layers: sliding window (512 or 1024 tokens)
- **Global** layers: full context, interleaved with local
- Final layer is always a global attention layer
#### PLE — Edge Models (E2B/E4B)
- Per-Layer Embeddings: each decoder layer has its own small embedding table
- Large static tables use fast lookups — not dense matrix multiply
- Effective compute parameters ≪ total loaded parameters
- Enables inference under 1.5 GB VRAM (with 4-bit quantization)
#### p-RoPE & Shared KV Cache
- Proportional RoPE (p-RoPE) on global layers for long-range coherence
- Shared KV Cache across global layers reduces peak memory usage
- Supports stable 256K context without performance degradation
#### MoE — 26B A4B
- 128 total experts + 1 always-active shared expert
- 8 experts activated per token at inference time
- Speed similar to a 4B dense model, quality near 30B
- Vision encoder: ~550M params (same as 31B)
### Memory Requirements
| Model | BF16 (16-bit) | 8-bit | 4-bit |
| ------- | ------------- | ------- | ------- |
| E2B | 9.6 GB | 4.6 GB | 3.2 GB |
| E4B | 15 GB | 7.5 GB | 5 GB |
| 31B | 58.3 GB | 30.4 GB | 17.4 GB |
| 26B A4B | 48 GB | 25 GB | 15.6 GB |
{.show-header}
Base weights only — add VRAM for KV cache.
### Pick a Model
| Available VRAM | Recommended |
| --------------- | ----------- |
| < 5 GB | E2B (4-bit) |
| 5–8 GB | E4B (4-bit) |
| 15–20 GB | E4B (BF16) |
| 24–32 GB | 31B (4-bit) |
| 48–80 GB | 31B (BF16) |
| High throughput | 26B A4B |
## Benchmarks {.cols-2}
### Core Benchmarks {.col-span-2 .row-span-2}
| Benchmark | 31B | 26B A4B | E4B | E2B | Gemma 3 27B |
| -------------------- | ----- | ------- | ----- | ----- | ----------- |
| MMLU Pro | 85.2% | 82.6% | 69.4% | 60.0% | 67.6% |
| MMMLU (multilingual) | 88.4% | 86.3% | 76.6% | 67.4% | 70.7% |
| AIME 2026 (math) | 89.2% | 88.3% | 42.5% | 37.5% | 20.8% |
| GPQA Diamond | 84.3% | 82.3% | 58.6% | 43.4% | 42.4% |
| LiveCodeBench v6 | 80.0% | 77.1% | 52.0% | 44.0% | 29.1% |
| Codeforces ELO | 2150 | 1718 | 940 | 633 | 110 |
| BigBench Extra Hard | 74.4% | 64.8% | 33.1% | 21.9% | 19.3% |
| Tau2 avg (agentic) | 76.9% | 68.2% | 42.2% | 24.5% | 16.2% |
| HLE no tools | 19.5% | 8.7% | — | — | — |
| HLE with search | 26.5% | 17.2% | — | — | — |
{.show-header}
All results for instruction-tuned models with thinking mode enabled.
### Vision Benchmarks
| Benchmark | 31B | 26B A4B | E4B | E2B |
| ------------- | ----- | ------- | ----- | ----- |
| MMMU Pro | 76.9% | 73.8% | 52.6% | 44.2% |
| MATH-Vision | 85.6% | 82.4% | 59.5% | 52.4% |
| MedXPertQA MM | 61.3% | 58.1% | 28.7% | 23.5% |
| OmniDocBench↓ | 0.131 | 0.149 | 0.181 | 0.290 |
{.show-header}
OmniDocBench = document edit distance (lower is better).
### Long Context
| Benchmark | 31B | 26B A4B | E4B | E2B |
| ------------ | ----- | ------- | ----- | ----- |
| MRCR v2 128K | 66.4% | 44.1% | 25.4% | 19.1% |
{.show-header}
#### Arena AI (LMSYS ELO)
| Model | ELO | Open Rank |
| --------------- | ---- | --------- |
| Gemma 4 31B | 1452 | #3 |
| Gemma 4 26B A4B | 1441 | #6 |
## Thinking Mode {.cols-2}
### Thinking Control {.row-span-2}
Add `<|think|>` to the **start** of the system prompt:
```python
messages = [
{
"role": "system",
"content": "<|think|>You are a math expert."
},
{"role": "user", "content": "Solve: 3x + 7 = 22"}
]
text = processor.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=True
)
outputs = model.generate(**inputs, max_new_tokens=2048)
response = processor.decode(
outputs[0][input_len:], skip_special_tokens=False
)
result = processor.parse_response(response)
# result["thinking"] → step-by-step reasoning
# result["response"] → final answer
```
#### Thinking output structure
```
<|channel>thought
[Internal step-by-step reasoning — hidden from user]
<channel|>
[Final answer visible to user]
```
#### Disabled thinking behavior
For 31B/26B A4B with `enable_thinking=False`, empty tags still emitted:
```
<|channel>thought
<channel|>
[Final answer]
```
E2B/E4B variants skip empty tags entirely when disabled.
### Control Tokens
| Token | Purpose |
| ---------------------- | -------------------------------- |
| `<\|think\|>` | Enable thinking in system prompt |
| `<\|channel>thought\n` | Open internal thought block |
| `<channel\|>` | Close thought block |
| `<\|turn>` | Open conversation turn |
| `<turn\|>` | Close conversation turn |
{.bold-first}
### Multi-turn Rules
- **Do not** include thought content in conversation history
- Pass only `result["response"]` as the model turn
- Longer `max_new_tokens` for complex reasoning tasks
- Use `enable_thinking=True` for AIME, proofs, debugging
## Multimodal {.cols-3}
### Image Inputs {.row-span-2}
Variable aspect ratio + configurable **visual token budget**:
| Budget | Best For |
| ------ | --------------------------------- |
| 70 | Fast classification, video frames |
| 140 | Captions, thumbnails |
| 280 | General image understanding |
| 560 | Charts, diagrams |
| 1120 | OCR, PDF parsing, fine detail |
```python
# Image MUST come before text (required)
messages = [{"role": "user", "content": [
{"type": "image", "image": image},
{"type": "text", "text": "Describe this chart."},
]}]
inputs = processor(
text=text,
images=image,
return_tensors="pt"
).to(model.device)
```
Vision encoder: ~150M params (E2B/E4B) · ~550M params (31B/26B)
### Audio Inputs
**E2B and E4B only** (~300M audio encoder)
- Max audio: **30 seconds**
- Tasks: ASR and speech translation
#### ASR prompt
```
Transcribe the following speech in
{LANGUAGE} into {LANGUAGE} text.
```
#### Translation prompt
```
Transcribe in {SRC_LANG}, then
translate to {TARGET_LANG}.
```
### Video Inputs
Processed as **sequential image frames**:
- Max: **60 seconds** at 1 fps = 60 frames
- Use **low token budget** (70–140) per frame
- E2B/E4B: also processes audio track simultaneously
```python
# Pass frames as list of images
inputs = processor(
text=text,
images=[frame1, frame2, ..., frame60],
return_tensors="pt"
)
```
### Modality Order {.secondary}
Always place **image/audio before text** in content:
```python
# ✅ Correct order
content = [
{"type": "image", "image": img},
{"type": "text", "text": "Describe it."},
]
# ❌ Text-first breaks alignment
content = [
{"type": "text", "text": "Describe it."},
{"type": "image", "image": img},
]
```
## Deployment {.cols-3}
### HuggingFace {.row-span-2}
```bash
$ pip install -U transformers accelerate
```
#### BF16 (default)
```python
from transformers import (
AutoProcessor, AutoModelForCausalLM
)
import torch
mid = "google/gemma-4-31b-it"
processor = AutoProcessor.from_pretrained(mid)
model = AutoModelForCausalLM.from_pretrained(
mid,
torch_dtype=torch.bfloat16,
device_map="auto"
)
```
#### 4-bit quantized
```python
from transformers import BitsAndBytesConfig
bnb = BitsAndBytesConfig(load_in_4bit=True)
model = AutoModelForCausalLM.from_pretrained(
mid,
quantization_config=bnb,
device_map="auto"
)
```
### Ollama
```bash
$ ollama pull gemma4 # 31B (default)
$ ollama pull gemma4:e4b # edge 4B variant
$ ollama pull gemma4:e2b # edge 2B variant
$ ollama run gemma4 # interactive chat
```
#### Custom GGUF (Modelfile)
```bash
FROM /path/to/fine-tuned.gguf
SYSTEM "You are a coding assistant."
```
```bash
$ ollama create mygemma -f Modelfile
$ ollama run mygemma
```
### vLLM Server
```bash
$ vllm serve google/gemma-4-31B-it \
--max-model-len 8192 \
--enable-auto-tool-choice \
--tool-call-parser gemma4 \
--reasoning-parser gemma4
```
OpenAI-compatible API at `http://localhost:8000/v1`
### Cloud & API
| Platform | Notes |
| ---------- | ------------------ |
| Gemini API | `gemma-4-31b-it` |
| AI Studio | Browser playground |
| Vertex AI | Custom endpoint |
| Cloud Run | Serverless GPU |
| GKE + vLLM | Auto-scale |
{.bold-first}
### Edge & Mobile
| Runtime | Best For |
| ---------------- | ----------------- |
| AICore (Android) | System-level API |
| LiteRT-LM | IoT, Raspberry Pi |
| AI Edge Gallery | On-device eval |
| LM Studio | Desktop GUI |
| llama.cpp | CPU/GPU hybrid |
{.bold-first}
## Fine-Tuning {.cols-2}
### QLoRA Setup {.row-span-2}
Single **16 GB GPU** (T4/free Colab or Kaggle):
```python
from unsloth import FastModel
model, tokenizer = FastModel.from_pretrained(
"google/gemma-4-E4B-it",
load_in_4bit=True,
max_seq_length=4096
)
model = FastModel.get_peft_model(
model,
r=16,
lora_alpha=16,
lora_dropout=0,
target_modules=[
"q_proj", "k_proj",
"v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj"
],
)
```
#### Vision fine-tuning (E2B / E4B)
```python
from unsloth import FastVisionModel
model, tokenizer = FastVisionModel.from_pretrained(
"google/gemma-4-E4B-it",
finetune_vision_layers=False, # freeze encoder
finetune_language_layers=True,
load_in_4bit=True,
)
```
### MoE Fine-tuning
For **26B A4B** — full fine-tune breaks expert routing:
- Use **LoRA bf16** only (never FFT)
- Start with `r=16`, `lora_alpha=16`
- Increase context length gradually after loss converges
- Avoid targeting expert router weight matrices
### Data Requirements
| Requirement | Value |
| ---------------- | ----------------------------- |
| CoT data ratio | ≥ 75% of training set |
| Thinking format | Include `<\|think\|>` trigger |
| Multimodal order | Images/audio before text |
| Chat template | ShareGPT or OpenAI format |
| RL reward | Verifiable final answer |
{.bold-first}
### Vision Fine-tune Tips
1. **Freeze vision first** — `finetune_vision_layers=False`
2. Fine-tune LLM + attention + MLP projectors only
3. Validate text-domain quality before unfreezing
4. Unfreeze vision only for domain-specific images
5. Low token budget (70–280) saves VRAM during training
## Gemmaverse {.cols-3}
### Specialist Models {.col-span-2}
| Model | Domain | Description |
| ------------- | --------------- | ----------------------------------- |
| MedGemma 4B | Medical imaging | Multimodal X-ray/MRI analysis |
| MedGemma 27B | Clinical text | EHR + medical report reasoning |
| CodeGemma | Coding | Code completion & refactoring |
| PaliGemma 2 | Visual-language | Fine-grained VLM & visual reasoning |
| ShieldGemma | Safety | LLM output safety classifier |
| DataGemma | Factual data | Grounded via Google Data Commons |
| FunctionGemma | Tool calling | Low-resource function call parsing |
{.show-header}
### Ecosystem
**Libraries & Frameworks**
- ADK (Agent Development Kit)
- JAX Gemma Library (`google-deepmind/gemma`)
- Gemma Cookbook (`google-gemma/gemma-cookbook`)
- `google/adk-samples` starter agents
**Community Variants**
- 100K+ community fine-tuned derivatives
- RecurrentGemma (Griffin architecture)
- EmbeddingGemma, T5Gemma 2
- VaultGemma (differential privacy)
## Also see {.cols-1}
- [Official Docs](https://ai.google.dev/gemma/docs/core) _(ai.google.dev)_
- [Model Card](https://ai.google.dev/gemma/docs/core/model_card_4) _(ai.google.dev)_
- [DeepMind Models Page](https://deepmind.google/models/gemma/gemma-4/) _(deepmind.google)_
- [HuggingFace](https://huggingface.co/google) _(huggingface.co)_
- [Gemma Cookbook](https://github.com/google-gemma/gemma-cookbook) _(github.com)_
- [JAX Gemma Library](https://github.com/google-deepmind/gemma) _(github.com)_
- [vLLM Usage Guide](https://docs.vllm.ai/projects/recipes/en/latest/Google/Gemma4.html) _(docs.vllm.ai)_
- [Ollama Library](https://ollama.com/library/gemma4) _(ollama.com)_
+720
View File
@@ -0,0 +1,720 @@
---
title: OpenClaw
date: 2026-04-03 10:00:00
background: bg-[#cc2200]
tags:
- whatsapp
- telegram
- ai-gateway
- automation
categories:
- AI
intro: |
[OpenClaw](https://openclaw.ai) is a self-hosted AI gateway that bridges WhatsApp, Telegram, Discord, iMessage, and more to AI coding agents.
plugins:
- copyCode
---
## Getting Started
### Quick Setup {.row-span-2}
#### 1. Install
```bash
# macOS / Linux / WSL2
curl -fsSL https://openclaw.ai/install.sh | bash
# or via npm
npm install -g openclaw@latest
```
#### 2. Onboard & install service
```bash
openclaw onboard --install-daemon
```
#### 3. Verify the gateway
```bash
openclaw gateway status
```
#### 4. Open dashboard
```bash
openclaw dashboard
# Local default: http://127.0.0.1:18789/
```
### Introduction
- [Docs](https://docs.openclaw.ai) _(docs.openclaw.ai)_
- [GitHub](https://github.com/openclaw/openclaw) _(github.com)_
- [Discord](https://discord.gg/openclaw) _(discord.gg)_
- [Releases](https://github.com/openclaw/openclaw/releases) _(github.com)_
Self-hosted, MIT licensed, multi-channel
### Alternative Install
```bash {.wrap}
# From source
git clone https://github.com/openclaw/openclaw.git
cd openclaw && pnpm install && pnpm build
pnpm link --global
```
### Verify Install
```bash
openclaw --version # confirm CLI available
openclaw doctor # health check + fixes
openclaw status # channels + gateway status
```
### Global Flags
| Flag | Description |
| -------------------- | ------------------------ |
| `--dev` | Dev profile, port 19001 |
| `--profile <name>` | Named isolated profile |
| `--container <name>` | Run inside a container |
| `--log-level <l>` | Log level (silent…trace) |
| `--no-color` | Disable ANSI colors |
{.bold-first}
## Gateway {.cols-2}
### Service Management {.row-span-2}
```bash
# Install as system service
openclaw gateway install
# Start / stop / restart
openclaw gateway start
openclaw gateway stop
openclaw gateway restart
# Uninstall service
openclaw gateway uninstall
```
#### Status & health
```bash
openclaw gateway status # service status + probe
openclaw gateway status --deep
openclaw gateway status --json
openclaw health # fetch health from gateway
openclaw logs --follow # tail gateway logs
```
### Startup Options
```bash
openclaw gateway run # foreground
openclaw gateway run --port 19001
openclaw gateway run --force # kill existing listener
openclaw gateway run --verbose # verbose to stdout
openclaw gateway run --bind lan # bind to LAN
openclaw gateway run --auth token --token <t>
```
### Hot Reload Modes
| `gateway.reload.mode` | Behavior |
| --------------------- | ------------------------------------------- |
| `hybrid` _(default)_ | Hot-apply safe changes, restart when needed |
| `hot` | Apply only hot-safe changes |
| `restart` | Restart on any reload-required change |
| `off` | No config reload |
{.show-header}
### Remote Access
```bash
# SSH tunnel (recommended fallback)
ssh -N -L 18789:127.0.0.1:18789 user@host
# then connect to ws://127.0.0.1:18789
# Tailscale (preferred for always-on)
openclaw gateway run --tailscale serve
```
### OpenAI-Compatible API
| Endpoint | Purpose |
| --------------------------- | --------------------- |
| `GET /v1/models` | List agents as models |
| `POST /v1/chat/completions` | Chat with agent |
| `POST /v1/responses` | Agent-native response |
| `POST /v1/embeddings` | Embedding pipeline |
All endpoints run on the main gateway port.
## Channels {.cols-2}
### Connect Channels {.row-span-2}
```bash
# List + status
openclaw channels list
openclaw channels status
openclaw channels status --probe
# Login (QR/OAuth flow)
openclaw channels login --channel whatsapp
openclaw channels login --channel telegram
# Add with token (non-interactive)
openclaw channels add \
--channel telegram --token <BOT_TOKEN>
# Logout / remove
openclaw channels logout --channel whatsapp
openclaw channels remove --channel telegram
# Logs + capabilities
openclaw channels logs
openclaw channels capabilities
```
#### Resolve contact IDs
```bash
openclaw directory self --channel telegram
openclaw directory peers list --channel slack
openclaw directory groups list --channel discord
```
### Supported Channels {.col-span-2}
#### Built-in
| Channel | Notes |
| ----------- | -------------------------------- |
| WhatsApp | QR pairing via Baileys |
| Telegram | Bot API — fastest to set up |
| Discord | Bot API + Gateway, DMs + servers |
| BlueBubbles | iMessage via macOS server |
| Signal | Via signal-cli |
| Slack | Bolt SDK workspace apps |
| Google Chat | HTTP webhook |
| IRC | Classic IRC, DMs + channels |
| QQ Bot | QQ Bot API |
| WebChat | Built-in browser chat UI |
{.show-header}
#### Via plugin (`openclaw plugins install`)
- Matrix
- Mattermost
- Microsoft Teams
- LINE
- Nextcloud Talk
- Feishu / Lark
- Nostr
- Synology Chat
- Twitch
- WeChat
- Zalo / Zalo Personal
- Voice Call (Plivo/Twilio)
{.cols-3 .marker-none}
## Messaging {.cols-2}
### Send Messages {.row-span-2}
```bash
# Basic text
openclaw message send \
--target +15555550123 --message "Hello"
# Telegram by username
openclaw message send \
--channel telegram --target @user \
--message "Hello"
# Discord channel
openclaw message send \
--channel discord --target channel:123 \
--message "Hello"
# With media
openclaw message send \
--target +15555550123 \
--media photo.jpg --message "Look"
# Silent (no notification)
openclaw message send \
--target +15555550123 \
--message "Quiet" --silent
# Reply to a message
openclaw message send \
--target +15555550123 \
--message "Reply" --reply-to <msg-id>
```
### Read Messages
```bash
openclaw message read \
--channel whatsapp --target +15555550123
openclaw message read \
--channel discord --target channel:123 \
--limit 20 --json
```
### Message Actions
```bash
# Broadcast to multiple targets
openclaw message broadcast \
--message "Alert" --targets @u1 @u2
# React to a message
openclaw message react \
--channel discord --target 123 \
--message-id 456 --emoji "✅"
# Pin / unpin
openclaw message pin \
--channel discord --target 123 \
--message-id 456
# Edit / delete
openclaw message edit --message-id 456
openclaw message delete --message-id 456
```
## Agents & Sessions {.cols-3}
### Run Agent {.row-span-2}
```bash
# New session
openclaw agent \
--to +15555550123 --message "Hello"
# Named agent
openclaw agent \
--agent ops --message "Status"
# With thinking level
openclaw agent \
--to +15555550123 \
--message "Analyze" --thinking high
# Deliver reply back to channel
openclaw agent \
--to +15555550123 \
--message "Summary" --deliver
# Cross-channel delivery
openclaw agent \
--agent ops --message "Report" \
--deliver \
--reply-channel slack \
--reply-to "#reports"
# JSON output + verbose
openclaw agent \
--to +15555550123 \
--message "Trace" --verbose on --json
```
### Manage Agents
```bash
openclaw agents list
openclaw agents list --bindings
openclaw agents add work
openclaw agents delete work
openclaw agents bind
openclaw agents unbind
openclaw agents bindings
openclaw agents set-identity \
--agent work --name "Work Bot"
```
### Sessions
```bash
openclaw sessions # all sessions
openclaw sessions --agent work
openclaw sessions --all-agents
openclaw sessions --active 120 # last 2h
openclaw sessions --json
openclaw sessions cleanup
```
### Routing Priority {.col-span-2}
| Priority | Match type |
| ----------- | ---------------------------------- |
| 1 (highest) | `peer` — exact DM/group/channel ID |
| 2 | `parentPeer` — thread inheritance |
| 3 | `guildId` + roles (Discord) |
| 4 | `guildId` (Discord) |
| 5 | `teamId` (Slack) |
| 6 | `accountId` match for channel |
| 7 | `accountId: "*"` channel fallback |
| 8 (lowest) | Default agent |
{.show-header}
## Models {.cols-2}
### Configure Models {.row-span-2}
```bash
# Set primary model
openclaw models set anthropic/claude-sonnet-4-6
# Set image model
openclaw models set-image openai/dall-e-3
# List models
openclaw models list # configured
openclaw models list --all # full catalog
openclaw models list --provider anthropic
# Status (auth + model overview)
openclaw models status
openclaw models status --check # exit 1 if missing
# Aliases
openclaw models aliases list
openclaw models aliases add Sonnet \
anthropic/claude-sonnet-4-6
openclaw models aliases remove Sonnet
# Fallback chains
openclaw models fallbacks list
openclaw models fallbacks add anthropic/claude-haiku-4-5
openclaw models fallbacks clear
```
### In-chat /model
```bash
/model # interactive picker
/model list # numbered model list
/model 3 # select by number
/model openai/gpt-4o
/model status # auth + provider details
```
Switch takes effect on the next agent run.
### Model Scan (OpenRouter)
```bash
# Scan free models (metadata only)
openclaw models scan --no-probe
# Full scan with capability probe
openclaw models scan \
--min-params 7 --max-age-days 30
# Auto-set best free model
openclaw models scan \
--set-default --yes
```
Requires `OPENROUTER_API_KEY` for probing.
## Config & Environment {.cols-2}
### Config Commands {.row-span-2}
```bash
# Show config file path
openclaw config file
# Get a value
openclaw config get gateway.port
openclaw config get channels.telegram.botToken
# Set a value
openclaw config set gateway.port 19001
openclaw config set \
agents.defaults.model.primary \
anthropic/claude-sonnet-4-6
# Unset a value
openclaw config unset gateway.port
# Validate config
openclaw config validate
# Print JSON schema
openclaw config schema
# Interactive guided setup
openclaw configure
```
### Environment Variables
| Variable | Description |
| --------------------------- | ---------------------- |
| `OPENCLAW_GATEWAY_PORT` | Gateway port |
| `OPENCLAW_GATEWAY_TOKEN` | Auth token |
| `OPENCLAW_GATEWAY_PASSWORD` | Auth password |
| `OPENCLAW_CONFIG_PATH` | Config file path |
| `OPENCLAW_STATE_DIR` | State directory |
| `OPENCLAW_PROFILE` | Active profile name |
| `OPENCLAW_CONTAINER` | Default container name |
{.bold-first}
### Default Paths
| Path | Description |
| ---------------------------------- | ------------------- |
| `~/.openclaw/openclaw.json` | Main config |
| `~/.openclaw/` | State directory |
| `~/.openclaw/workspace` | Agent workspace |
| `~/.openclaw/agents/<id>/agent` | Agent auth + models |
| `~/.openclaw/agents/<id>/sessions` | Session store |
| `~/.openclaw/credentials/` | Channel credentials |
| `~/.openclaw/skills/` | Shared skills |
{.bold-first}
## Memory & Backup {.cols-3}
### Memory Search
```bash
openclaw memory status
openclaw memory status --deep # probe embedding
openclaw memory index --force # full reindex
openclaw memory search "notes"
openclaw memory search \
--query "deploy" --max-results 20
openclaw memory status --json
```
### Backup & Restore
```bash
# Create backup archive
openclaw backup create
# Verify backup integrity
openclaw backup verify backup.tar.gz
```
Backs up: config, credentials, sessions, workspaces.
### Reset & Update
```bash
# Reset config + state (keeps CLI)
openclaw reset
# Update to latest
openclaw update
openclaw update --channel beta
openclaw update --channel dev
openclaw update --dry-run
# Full uninstall
openclaw uninstall
```
## Plugins & Skills {.cols-3}
### Plugin Commands {.row-span-2}
```bash
# Discover + inspect
openclaw plugins list
openclaw plugins inspect <name>
openclaw plugins marketplace
# Install (path / npm / clawhub)
openclaw plugins install clawhub:mattermost
openclaw plugins install ./my-plugin
openclaw plugins install @org/pkg@latest
# Enable / disable
openclaw plugins enable <name>
openclaw plugins disable <name>
# Update + uninstall
openclaw plugins update
openclaw plugins uninstall <name>
# Diagnose load issues
openclaw plugins doctor
```
### Skill Commands
```bash
openclaw skills list
openclaw skills check # readiness check
openclaw skills info <name>
openclaw skills search "browser"
openclaw skills install clawhub:browser
openclaw skills update
```
### Hook Commands
```bash
openclaw hooks list
openclaw hooks info <name>
openclaw hooks check
openclaw hooks enable <name>
openclaw hooks disable <name>
```
## Ops & Maintenance {.cols-2}
### Health & Diagnostics {.row-span-2}
```bash
# Quick health checks
openclaw health # gateway health
openclaw doctor # check + suggest fixes
openclaw doctor --fix # apply safe fixes
openclaw status # channels + sessions
openclaw logs --follow # tail log file
# Channel readiness
openclaw channels status --probe
# Gateway probe (full)
openclaw gateway probe
openclaw gateway status --deep --json
# Security audit
openclaw security audit
openclaw security audit --deep
openclaw security audit --fix
openclaw security audit --json
```
### Cron Jobs
```bash
openclaw cron list
openclaw cron status
# Add job (every / cron / at)
openclaw cron add \
--name "daily" \
--every 24h \
--message "Daily summary" \
--agent main --announce
openclaw cron add \
--cron "0 9 * * *" \
--message "Morning brief" \
--tz America/New_York
openclaw cron enable <id>
openclaw cron disable <id>
openclaw cron edit <id>
openclaw cron rm <id>
openclaw cron run <id> # debug: run now
openclaw cron runs # run history
```
### Nodes (iOS/Android)
```bash
# List + status
openclaw nodes list
openclaw nodes status
# Pairing
openclaw qr # iOS QR code
openclaw nodes pending
openclaw nodes approve --node <id>
openclaw nodes reject --node <id>
# Media capture
openclaw nodes camera snap --node <id>
openclaw nodes canvas --node <id>
openclaw nodes screen --node <id>
openclaw nodes location --node <id>
# Invoke + notify
openclaw nodes invoke \
--node <id> \
--command system.which \
--params '{"name":"uname"}'
openclaw nodes notify \
--node <id> --message "Hello"
```
### Security Controls
```bash
# DM pairing
openclaw pairing list
openclaw pairing approve <code>
# Exec approvals
openclaw approvals get
openclaw approvals allowlist
openclaw approvals set --file approvals.json
# Device tokens
openclaw devices list
openclaw devices revoke --role admin
openclaw devices rotate --role admin
```
### Multi-agent Config {.col-span-2}
```json
{
"agents": {
"list": [
{
"id": "chat",
"workspace": "~/.openclaw/workspace-chat",
"model": "anthropic/claude-sonnet-4-6"
},
{
"id": "work",
"workspace": "~/.openclaw/workspace-work",
"model": "anthropic/claude-opus-4-6"
}
]
},
"bindings": [
{ "agentId": "chat", "match": { "channel": "whatsapp" } },
{ "agentId": "work", "match": { "channel": "telegram" } }
],
"channels": {
"whatsapp": { "dmPolicy": "pairing" },
"telegram": { "accounts": { "default": { "botToken": "TOKEN" } } }
},
"gateway": { "port": 18789, "bind": "loopback" }
}
```
Config lives at `~/.openclaw/openclaw.json` (JSON5 format)
## Also see {.cols-1}
- [Official Documentation](https://docs.openclaw.ai) _(docs.openclaw.ai)_
- [GitHub Repository](https://github.com/openclaw/openclaw) _(github.com)_
- [Discord Community](https://discord.gg/openclaw) _(discord.gg)_
- [Releases & Changelog](https://github.com/openclaw/openclaw/releases) _(github.com)_
- [CLI Reference](https://docs.openclaw.ai/cli) _(docs.openclaw.ai)_
- [Model Providers](https://docs.openclaw.ai/models) _(docs.openclaw.ai)_
- [Channel Setup Guides](https://docs.openclaw.ai/channels) _(docs.openclaw.ai)_