gemini-reference

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Gemini CLI Reference

Gemini CLI 参考文档

Invoke the Gemini agent for sub-tasks using structured JSON output and explicit session management.
使用结构化JSON输出和显式会话管理,调用Gemini Agent处理子任务。

When to Use Gemini

何时使用Gemini

Use Gemini when you need:
  • Large context window - Can process extensive codebases in one pass
  • General purpose tasks - Good balance of capability across domains
  • Fast responses - Flash models for quick analysis
  • Cost efficiency - Lower cost per token for large inputs
在以下场景中使用Gemini:
  • 大上下文窗口 - 可一次性处理大型代码库
  • 通用任务 - 在各领域能力间达到良好平衡
  • 快速响应 - 采用Flash模型实现快速分析
  • 成本高效 - 处理大输入时每token成本更低

Capabilities

功能特性

  • Core Tools:
    ReadFileTool
    ,
    WriteFile
    ,
    Edit
    ,
    GlobTool
    ,
    GrepTool
    ,
    ShellTool
    .
  • MCP Servers:
    • context7
      : Documentation queries.
    • brave-search
      : Web search (Brave).
  • Specialty: General purpose, large context window.
  • 核心工具
    ReadFileTool
    WriteFile
    Edit
    GlobTool
    GrepTool
    ShellTool
  • MCP服务器:
    • context7
      : 文档查询。
    • brave-search
      : 网页搜索(基于Brave)。
  • 专长:通用用途、大上下文窗口。

Calling from Another Agent

从其他Agent调用

Use
gemini "prompt"
to spawn Gemini as a sub-agent:
bash
undefined
使用
gemini "prompt"
启动Gemini作为子Agent:
bash
undefined

Delegate a documentation task

委托文档生成任务

result=$(gemini "Generate API documentation for @src/api/" --output-format json)
result=$(gemini "Generate API documentation for @src/api/" --output-format json)

Extract the response and session_id for follow-up

提取响应和session_id以便后续操作

response=$(echo "$result" | jq -r '.response') session_id=$(echo "$result" | jq -r '.session_id')
undefined
response=$(echo "$result" | jq -r '.response') session_id=$(echo "$result" | jq -r '.session_id')
undefined

Output Formats

输出格式

FormatDescription
text
(default)
Plain text output
json
Single JSON object with
response
,
stats
,
session_id
stream-json
Streaming newline-delimited JSON (JSONL) events
JSON Response Fields:
  • response
    : (string) The model's final answer
  • stats
    : (object) Token usage and API latency metrics
  • session_id
    : (string) Session identifier for resuming
  • error
    : (object, optional) Error details if request failed
Streaming JSON Event Types:
  • init
    : Session metadata (session ID, model)
  • message
    : User and assistant message chunks
  • tool_use
    : Tool call requests with arguments
  • tool_result
    : Output from executed tools
  • error
    : Non-fatal warnings and system errors
  • result
    : Final outcome with aggregated statistics
格式描述
text
(默认)
纯文本输出
json
包含
response
stats
session_id
的单个JSON对象
stream-json
流式换行分隔JSON(JSONL)事件
JSON响应字段:
  • response
    : (字符串) 模型的最终回答
  • stats
    : (对象) Token使用量和API延迟指标
  • session_id
    : (字符串) 用于恢复会话的标识符
  • error
    : (对象,可选) 请求失败时的错误详情
流式JSON事件类型:
  • init
    : 会话元数据(会话ID、模型信息)
  • message
    : 用户和助手消息片段
  • tool_use
    : 包含参数的工具调用请求
  • tool_result
    : 已执行工具的输出
  • error
    : 非致命警告和系统错误
  • result
    : 包含聚合统计数据的最终结果

Handling Blocked Actions

处理被阻止的操作

When Gemini needs approval for an action it wasn't configured to auto-approve, the command may pause or complete with an error. For agent delegation:
bash
undefined
当Gemini需要执行未配置为自动批准的操作时,命令可能会暂停或返回错误。对于Agent委托场景:
bash
undefined

Step 1: Initial attempt with conservative permissions

步骤1:使用保守权限进行首次尝试

result=$(gemini "Fix the build errors" --output-format json --approval-mode default)
result=$(gemini "Fix the build errors" --output-format json --approval-mode default)

Step 2: Check for errors

步骤2:检查错误

if echo "$result" | jq -e '.error' > /dev/null 2>&1; then error_msg=$(echo "$result" | jq -r '.error.message') echo "Action blocked: $error_msg" session_id=$(echo "$result" | jq -r '.session_id')

Step 3: Continue with auto_edit mode for file operations

echo "Continue fixing build errors" > /tmp/continue.md result=$(gemini "Read /tmp/continue.md"
--resume "$session_id"
--output-format json
--approval-mode auto_edit) fi
if echo "$result" | jq -e '.error' > /dev/null 2>&1; then error_msg=$(echo "$result" | jq -r '.error.message') echo "Action blocked: $error_msg" session_id=$(echo "$result" | jq -r '.session_id')

步骤3:使用auto_edit模式继续处理文件操作

echo "Continue fixing build errors" > /tmp/continue.md result=$(gemini "Read /tmp/continue.md"
--resume "$session_id"
--output-format json
--approval-mode auto_edit) fi

Extract final response

提取最终响应

final_response=$(echo "$result" | jq -r '.response')
undefined
final_response=$(echo "$result" | jq -r '.response')
undefined

Session Management for Agent Delegation

Agent委托的会话管理

Starting a Task

启动任务

bash
mkdir -p .gemini/sessions
echo "*" > .gemini/.gitignore
bash
mkdir -p .gemini/sessions
echo "*" > .gemini/.gitignore

Write the task with full context

写入包含完整上下文的任务

cat > .gemini/sessions/task.md << 'EOF' Review @src/auth/ and identify:
  1. Authentication vulnerabilities
  2. Missing input validation
  3. Improper error handling EOF
cat > .gemini/sessions/task.md << 'EOF' Review @src/auth/ and identify:
  1. Authentication vulnerabilities
  2. Missing input validation
  3. Improper error handling EOF

Spawn Gemini with scoped permissions

使用限定权限启动Gemini

result=$(gemini "Read .gemini/sessions/task.md"
--output-format json
--approval-mode default)
result=$(gemini "Read .gemini/sessions/task.md"
--output-format json
--approval-mode default)

Capture session info

捕获会话信息

session_id=$(echo "$result" | jq -r '.session_id') rm .gemini/sessions/task.md
undefined
session_id=$(echo "$result" | jq -r '.session_id') rm .gemini/sessions/task.md
undefined

Resuming a Session

恢复会话

Continue a specific session when you have the
session_id
:
bash
echo "Implement fixes for the top 3 issues you found" > .gemini/sessions/continue.md

result=$(gemini "Read .gemini/sessions/continue.md" \
  --resume "$session_id" \
  --output-format json \
  --approval-mode auto_edit)

rm .gemini/sessions/continue.md
Resume Options:
FlagDescription
--resume <id>
Resume specific session by ID or UUID
--resume "latest"
Resume most recent session
--resume 5
Resume by index number
--list-sessions
List available sessions
Important: Always use explicit
--resume
with session ID when calling from another agent.
当你拥有
session_id
时,可继续特定会话:
bash
echo "Implement fixes for the top 3 issues you found" > .gemini/sessions/continue.md

result=$(gemini "Read .gemini/sessions/continue.md" \
  --resume "$session_id" \
  --output-format json \
  --approval-mode auto_edit)

rm .gemini/sessions/continue.md
恢复选项:
标志描述
--resume <id>
通过ID或UUID恢复特定会话
--resume "latest"
恢复最近的会话
--resume 5
通过索引编号恢复会话
--list-sessions
列出可用会话
重要提示: 从其他Agent调用时,务必使用带会话ID的显式
--resume
参数。

Permission Handling

权限处理

By default, Gemini requests confirmation for actions that modify your system. When calling from another agent, use
--approval-mode
:
默认情况下,Gemini会在执行修改系统的操作前请求确认。从其他Agent调用时,使用
--approval-mode
参数:

--approval-mode

--approval-mode

Set the approval mode for tool execution:
ModeDescription
default
Prompt for permission on sensitive actions
auto_edit
Automatically approve file edits only
bash
undefined
设置工具执行的批准模式:
模式描述
default
对敏感操作提示获取权限
auto_edit
自动批准仅文件编辑操作
bash
undefined

Safe for file editing tasks

适用于文件编辑任务

gemini "Fix lint errors" --approval-mode auto_edit
gemini "Fix lint errors" --approval-mode auto_edit

For analysis tasks (no modifications)

适用于分析任务(无修改操作)

gemini "Analyze codebase" --approval-mode default
undefined
gemini "Analyze codebase" --approval-mode default
undefined

--sandbox

--sandbox

Run in a sandboxed environment for safer execution:
bash
undefined
在沙箱环境中运行以提升执行安全性:
bash
undefined

Sandbox for untrusted code

为不可信代码提供沙箱

gemini "Run untrusted code" --sandbox gemini "Analyze suspicious file" --sandbox --output-format json
undefined
gemini "Run untrusted code" --sandbox gemini "Analyze suspicious file" --sandbox --output-format json
undefined

--full-auto

--full-auto

Shortcut for automation: sets
--approval-mode auto_edit
and
--sandbox workspace-write
.
bash
gemini "Fix lint errors and run tests" --full-auto
自动化快捷方式:同时设置
--approval-mode auto_edit
--sandbox workspace-write
bash
gemini "Fix lint errors and run tests" --full-auto

Agent Delegation Patterns

Agent委托模式

Pattern 1: Analysis → Implementation

模式1:分析 → 实现

bash
undefined
bash
undefined

Phase 1: Analysis (default approvals)

阶段1:分析(默认批准模式)

analyze_result=$(gemini "Explore @src/ to understand the codebase structure"
--output-format json --approval-mode default)
session_id=$(echo "$analyze_result" | jq -r '.session_id')
analyze_result=$(gemini "Explore @src/ to understand the codebase structure"
--output-format json --approval-mode default)
session_id=$(echo "$analyze_result" | jq -r '.session_id')

Phase 2: Implementation (auto_edit for file changes)

阶段2:实现(文件变更使用auto_edit模式)

impl_result=$(gemini "Implement a logging middleware"
--resume "$session_id" --output-format json
--approval-mode auto_edit)
undefined
impl_result=$(gemini "Implement a logging middleware"
--resume "$session_id" --output-format json
--approval-mode auto_edit)
undefined

Pattern 2: Escalating Permissions

模式2:权限升级

bash
undefined
bash
undefined

Start conservative

以保守权限启动

result=$(gemini "Fix the bug" --output-format json --approval-mode default)
result=$(gemini "Fix the bug" --output-format json --approval-mode default)

Check for errors

检查错误

if echo "$result" | jq -e '.error' > /dev/null 2>&1; then session_id=$(echo "$result" | jq -r '.session_id')

Re-run with broader permissions

result=$(gemini "Continue fixing with edit permissions"
--resume "$session_id" --output-format json
--approval-mode auto_edit) fi
undefined
if echo "$result" | jq -e '.error' > /dev/null 2>&1; then session_id=$(echo "$result" | jq -r '.session_id')

使用更广泛的权限重新运行

result=$(gemini "Continue fixing with edit permissions"
--resume "$session_id" --output-format json
--approval-mode auto_edit) fi
undefined

Pattern 3: Model Selection by Task

模式3:按任务选择模型

bash
undefined
bash
undefined

Quick analysis - use flash

快速分析 - 使用flash模型

gemini "Summarize this file" --model flash --output-format json
gemini "Summarize this file" --model flash --output-format json

Complex reasoning - use pro

复杂推理 - 使用pro模型

gemini "Design a distributed system architecture" --model pro --output-format json
gemini "Design a distributed system architecture" --model pro --output-format json

Balanced - use auto (default)

平衡选择 - 使用auto(默认)

gemini "Implement feature X" --model auto --output-format json
undefined
gemini "Implement feature X" --model auto --output-format json
undefined

Code Review Delegation

代码审查委托

To delegate code review to Gemini:
bash
mkdir -p .gemini/sessions
echo "Run 'jj diff -s -r @-' and 'jj diff -r @-' and review the output." > .gemini/sessions/review.md

result=$(gemini "Read .gemini/sessions/review.md" \
  --output-format json \
  --approval-mode default)

rm .gemini/sessions/review.md
Important: Do not use
--approval-mode auto_edit
during reviews - keep it read-only.
将代码审查任务委托给Gemini:
bash
mkdir -p .gemini/sessions
echo "Run 'jj diff -s -r @-' and 'jj diff -r @-' and review the output." > .gemini/sessions/review.md

result=$(gemini "Read .gemini/sessions/review.md" \
  --output-format json \
  --approval-mode default)

rm .gemini/sessions/review.md
重要提示: 审查期间请勿使用
--approval-mode auto_edit
- 保持只读模式。

Additional Useful Flags

其他实用标志

FlagDescription
--model
,
-m
Model to use (auto/pro/flash/flash-lite)
--output-format
,
-o
Output format (text/json/stream-json)
--sandbox
,
-s
Run in sandbox
--include-directories
Add directories to workspace
--extensions
,
-e
Enable specific extensions
--allowed-mcp-server-names
Allow specific MCP servers
--debug
,
-d
Debug mode with verbose logging
标志描述
--model
,
-m
使用的模型(auto/pro/flash/flash-lite)
--output-format
,
-o
输出格式(text/json/stream-json)
--sandbox
,
-s
在沙箱中运行
--include-directories
将目录添加到工作区
--extensions
,
-e
启用特定扩展
--allowed-mcp-server-names
允许特定MCP服务器
--debug
,
-d
调试模式,含详细日志

Model Selection

模型选择

AliasDescription
auto
Default. Resolves to preview model if enabled, else pro
pro
Complex reasoning tasks
flash
Fast, balanced for most tasks
flash-lite
Fastest for simple tasks
别名描述
auto
默认值。 若启用预览模型则使用预览模型,否则使用pro模型
pro
复杂推理任务
flash
速度快,适用于大多数任务
flash-lite
速度最快,适用于简单任务

Piping Input

管道输入

Feed data into Gemini using Unix pipes:
bash
undefined
使用Unix管道向Gemini提供数据:
bash
undefined

Pipe a file

管道传输文件内容

cat error.log | gemini "Explain why this failed"
cat error.log | gemini "Explain why this failed"

Pipe command output

管道传输命令输出

git diff | gemini "Write a commit message for these changes"
git diff | gemini "Write a commit message for these changes"

Combined with file references

与文件引用结合使用

gemini "Review @package.json and explain the dependencies"
undefined
gemini "Review @package.json and explain the dependencies"
undefined

Best Practices for Agent Delegation

Agent委托最佳实践

Prompting

提示词

  • Be Specific: Provide clear goals, file paths, and constraints.
  • Include Context: Use
    @path/to/file
    to reference files explicitly.
  • Headless Context: Gemini can't see your context - include everything in the prompt.
  • 明确具体: 提供清晰的目标、文件路径和约束条件。
  • 包含上下文: 使用
    @path/to/file
    显式引用文件。
  • 无头上下文: Gemini无法感知你的本地上下文 - 需在提示词中包含所有必要信息。

Permission Safety

权限安全

  • Start Conservative: Use
    --approval-mode default
    initially.
  • Escalate as Needed: Check
    .error
    field and re-run with
    auto_edit
    .
  • Sandbox Untrusted Code: Always use
    --sandbox
    when running untrusted code.
  • 从保守权限开始: 初始使用
    --approval-mode default
  • 按需升级权限: 检查
    .error
    字段后,使用
    auto_edit
    重新运行。
  • 沙箱处理不可信代码: 运行不可信代码时始终使用
    --sandbox

Session Management

会话管理

  • Always Extract session_id: Capture it from JSON output.
  • Check for Errors: Always inspect the
    .error
    field in JSON response.
  • Session per Task: Use separate sessions for unrelated tasks.
  • 务必提取session_id: 从JSON输出中捕获会话ID。
  • 检查错误: 始终检查JSON响应中的
    .error
    字段。
  • 按任务分配会话: 为不相关任务使用独立会话。

Model Selection

模型选择

  • flash: Quick summaries, simple tasks
  • pro: Complex architecture, security reviews
  • auto: Let Gemini decide based on prompt
  • flash: 快速摘要、简单任务
  • pro: 复杂架构设计、安全审查
  • auto: 让Gemini根据提示词自动选择

Example: Complete Agent Delegation Workflow

示例:完整Agent委托工作流

bash
#!/bin/bash
bash
#!/bin/bash

1. Create temp directory

1. 创建临时目录

mkdir -p tmp/.gemini && echo "*" > tmp/.gitignore
mkdir -p tmp/.gemini && echo "*" > tmp/.gitignore

2. Write task with full context

2. 写入包含完整上下文的任务

cat > tmp/task.md << 'EOF' Analyze the codebase and provide:
  1. Architecture overview
  2. Potential security issues
  3. Performance bottlenecks
Focus on @src/ and @config/ directories. EOF
cat > tmp/task.md << 'EOF' Analyze the codebase and provide:
  1. Architecture overview
  2. Potential security issues
  3. Performance bottlenecks
Focus on @src/ and @config/ directories. EOF

3. Spawn Gemini with initial permissions (read-only)

3. 使用初始权限(只读)启动Gemini

result=$(gemini "Read tmp/task.md"
--output-format json
--approval-mode default)
result=$(gemini "Read tmp/task.md"
--output-format json
--approval-mode default)

4. Check for errors

4. 检查错误

if echo "$result" | jq -e '.error' > /dev/null 2>&1; then echo "Error: $(echo "$result" | jq -r '.error.message')" exit 1 fi
if echo "$result" | jq -e '.error' > /dev/null 2>&1; then echo "Error: $(echo "$result" | jq -r '.error.message')" exit 1 fi

5. Extract results

5. 提取结果

response=$(echo "$result" | jq -r '.response') session_id=$(echo "$result" | jq -r '.session_id') stats=$(echo "$result" | jq -r '.stats')
response=$(echo "$result" | jq -r '.response') session_id=$(echo "$result" | jq -r '.session_id') stats=$(echo "$result" | jq -r '.stats')

6. Report findings to parent agent

6. 向父Agent报告结果

echo "=== Analysis Complete ===" echo "Session ID: $session_id" echo "Token usage: $(echo "$stats" | jq -r '.total_tokens // "N/A"')" echo "" echo "$response"
echo "=== Analysis Complete ===" echo "Session ID: $session_id" echo "Token usage: $(echo "$stats" | jq -r '.total_tokens // "N/A"')" echo "" echo "$response"

7. Optional: Continue for implementation

7. 可选:继续执行实现步骤

echo "Now implement the security fixes" > tmp/implement.md

echo "Now implement the security fixes" > tmp/implement.md

gemini "Read tmp/implement.md" --resume "$session_id" --approval-mode auto_edit ...

gemini "Read tmp/implement.md" --resume "$session_id" --approval-mode auto_edit ...

8. Clean up

8. 清理

rm -rf tmp
undefined
rm -rf tmp
undefined

Exit Codes

退出码

CodeMeaning
0
Success
1
General error or API failure
42
Input error (invalid prompt or arguments)
53
Turn limit exceeded
代码含义
0
成功
1
通用错误或API失败
42
输入错误(无效提示词或参数)
53
超出轮次限制

Structured Output with Schema

带Schema的结构化输出

Request JSON output matching a JSON Schema:
bash
undefined
请求匹配JSON Schema的JSON输出:
bash
undefined

Create schema file

创建Schema文件

cat > /tmp/schema.json << 'EOF' { "type": "object", "properties": { "project_name": { "type": "string" }, "programming_languages": { "type": "array", "items": { "type": "string" } } }, "required": ["project_name", "programming_languages"] } EOF
cat > /tmp/schema.json << 'EOF' { "type": "object", "properties": { "project_name": { "type": "string" }, "programming_languages": { "type": "array", "items": { "type": "string" } } }, "required": ["project_name", "programming_languages"] } EOF

Run with schema

使用Schema运行

gemini "Extract project metadata from @package.json"
--output-schema /tmp/schema.json
-o /tmp/result.json
--output-format json
undefined
gemini "Extract project metadata from @package.json"
--output-schema /tmp/schema.json
-o /tmp/result.json
--output-format json
undefined