Gemini CLI 配置
¥Gemini CLI Configuration
Gemini CLI 提供了多种配置其行为的方式,包括环境变量、命令行参数和设置文件。本文档概述了不同的配置方法和可用的设置。
¥Gemini CLI offers several ways to configure its behavior, including environment variables, command-line arguments, and settings files. This document outlines the different configuration methods and available settings.
配置层
¥Configuration layers
配置按以下优先顺序应用(较低的数字被较高的数字覆盖):
¥Configuration is applied in the following order of precedence (lower numbers are overridden by higher numbers):
默认值:应用程序内的硬编码默认值。
¥Default values: Hardcoded defaults within the application.
系统默认文件:可以被其他设置文件覆盖的系统范围默认设置。
¥System defaults file: System-wide default settings that can be overridden by other settings files.
用户设置文件:当前用户的全局设置。
¥User settings file: Global settings for the current user.
项目设置文件:项目特定的设置。
¥Project settings file: Project-specific settings.
系统设置文件:覆盖所有其他设置文件的系统范围设置。
¥System settings file: System-wide settings that override all other settings files.
环境变量:系统范围或会话特定的变量,可能从
.env文件。¥Environment variables: System-wide or session-specific variables, potentially loaded from
.envfiles.命令行参数:启动 CLI 时传递的值。
¥Command-line arguments: Values passed when launching the CLI.
设置文件
¥Settings files
Gemini CLI 使用 JSON 设置文件进行持久化配置。这些文件位于以下四个位置:
¥Gemini CLI uses JSON settings files for persistent configuration. There are four locations for these files:
系统默认文件:
¥System defaults file:
地点:
/etc/gemini-cli/system-defaults.json(Linux)C:\ProgramData\gemini-cli\system-defaults.json(Windows)或/Library/Application Support/GeminiCli/system-defaults.json(macOS)。可以使用GEMINI_CLI_SYSTEM_DEFAULTS_PATH环境变量。¥Location:
/etc/gemini-cli/system-defaults.json(Linux),C:\ProgramData\gemini-cli\system-defaults.json(Windows) or/Library/Application Support/GeminiCli/system-defaults.json(macOS). The path can be overridden using theGEMINI_CLI_SYSTEM_DEFAULTS_PATHenvironment variable.范围:提供系统范围默认设置的基础层。这些设置的优先级最低,旨在被用户、项目或系统覆盖设置覆盖。
¥Scope: Provides a base layer of system-wide default settings. These settings have the lowest precedence and are intended to be overridden by user, project, or system override settings.
用户设置文件:
¥User settings file:
地点:
~/.gemini/settings.json(在哪里~是你的主目录)。¥Location:
~/.gemini/settings.json(where~is your home directory).范围:适用于当前用户的所有 Gemini CLI 会话。用户设置将覆盖系统默认设置。
¥Scope: Applies to all Gemini CLI sessions for the current user. User settings override system defaults.
项目设置文件:
¥Project settings file:
地点:
.gemini/settings.json在您的项目的根目录中。¥Location:
.gemini/settings.jsonwithin your project's root directory.范围:仅在从特定项目运行 Gemini CLI 时适用。项目设置会覆盖用户设置和系统默认值。
¥Scope: Applies only when running Gemini CLI from that specific project. Project settings override user settings and system defaults.
系统设置文件:
¥System settings file:
地点:
/etc/gemini-cli/settings.json(Linux)C:\ProgramData\gemini-cli\settings.json(Windows)或/Library/Application Support/GeminiCli/settings.json(macOS)。可以使用GEMINI_CLI_SYSTEM_SETTINGS_PATH环境变量。¥Location:
/etc/gemini-cli/settings.json(Linux),C:\ProgramData\gemini-cli\settings.json(Windows) or/Library/Application Support/GeminiCli/settings.json(macOS). The path can be overridden using theGEMINI_CLI_SYSTEM_SETTINGS_PATHenvironment variable.范围:适用于系统上所有用户的所有 Gemini CLI 会话。系统设置将覆盖所有其他设置文件。对于企业系统管理员来说,这可能有助于控制用户的 Gemini CLI 设置。
¥Scope: Applies to all Gemini CLI sessions on the system, for all users. System settings act as overrides, taking precedence over all other settings files. May be useful for system administrators at enterprises to have controls over users' Gemini CLI setups.
关于设置中的环境变量的注意事项:字符串值settings.json文件可以使用以下方式引用环境变量$VAR_NAME或者${VAR_NAME}语法。这些变量将在加载设置时自动解析。例如,如果您有一个环境变量MY_API_TOKEN,你可以使用它settings.json像这样:"apiKey": "$MY_API_TOKEN"。
¥Note on environment variables in settings: String values within your settings.json files can reference environment variables using either $VAR_NAME or ${VAR_NAME} syntax. These variables will be automatically resolved when the settings are loaded. For example, if you have an environment variable MY_API_TOKEN, you could use it in settings.json like this: "apiKey": "$MY_API_TOKEN".
企业用户须知:有关在企业环境中部署和管理 Gemini CLI 的指导,请参阅企业配置文档。
¥Note for Enterprise Users: For guidance on deploying and managing Gemini CLI in a corporate environment, please see the Enterprise Configuration documentation.
这.gemini项目中的目录
¥The .gemini directory in your project
除了项目设置文件之外,项目的.gemini目录可以包含与 Gemini CLI 操作相关的其他项目特定文件,例如:
¥In addition to a project settings file, a project's .gemini directory can contain other project-specific files related to Gemini CLI's operation, such as:
自定义沙盒配置文件(例如,
.gemini/sandbox-macos-custom.sb,.gemini/sandbox.Dockerfile)。¥Custom sandbox profiles (e.g.,
.gemini/sandbox-macos-custom.sb,.gemini/sandbox.Dockerfile).
可用设置settings.json:
¥Available settings in settings.json:
contextFileName(字符串或字符串数组):¥
contextFileName(string or array of strings):描述:指定上下文文件的文件名(例如,
GEMINI.md,AGENTS.md)。可以是单个文件名或可接受文件名的列表。¥Description: Specifies the filename for context files (e.g.,
GEMINI.md,AGENTS.md). Can be a single filename or a list of accepted filenames.默认:
GEMINI.md¥Default:
GEMINI.md-
例子:
"contextFileName": "AGENTS.md"¥Example:
"contextFileName": "AGENTS.md" -
bugCommand(目的):¥
bugCommand(object): 描述:覆盖默认 URL
/bug命令。¥Description: Overrides the default URL for the
/bugcommand.默认:
"urlTemplate": "https://github.com/google-gemini/gemini-cli/issues/new?template=bug_report.yml&title={title}&info={info}"¥Default:
"urlTemplate": "https://github.com/google-gemini/gemini-cli/issues/new?template=bug_report.yml&title={title}&info={info}"特性:
¥Properties:
urlTemplate(字符串):可以包含的 URL{title}和{info}占位符。¥
urlTemplate(string): A URL that can contain{title}and{info}placeholders.
-
例子:
json "bugCommand": { "urlTemplate": "https://bug.example.com/new?title={title}&info={info}" }¥Example:
json "bugCommand": { "urlTemplate": "https://bug.example.com/new?title={title}&info={info}" } -
fileFiltering(目的):¥
fileFiltering(object): 描述:控制@命令和文件发现工具的 git-aware 文件过滤行为。
¥Description: Controls git-aware file filtering behavior for @ commands and file discovery tools.
默认:
"respectGitIgnore": true, "enableRecursiveFileSearch": true¥Default:
"respectGitIgnore": true, "enableRecursiveFileSearch": true特性:
¥Properties:
respectGitIgnore(布尔值): 发现文件时是否遵循 .gitignore 模式。设置为true、git忽略的文件(例如node_modules/,dist/,.env) 将自动排除在 @ 命令和文件列表操作之外。¥
respectGitIgnore(boolean): Whether to respect .gitignore patterns when discovering files. When set totrue, git-ignored files (likenode_modules/,dist/,.env) are automatically excluded from @ commands and file listing operations.enableRecursiveFileSearch(布尔值): 在提示中完成 @ 前缀时是否启用在当前树下递归搜索文件名。¥
enableRecursiveFileSearch(boolean): Whether to enable searching recursively for filenames under the current tree when completing @ prefixes in the prompt.disableFuzzySearch(布尔值): 当true,在搜索文件时禁用模糊搜索功能,这可以提高具有大量文件的项目的性能。¥
disableFuzzySearch(boolean): Whentrue, disables the fuzzy search capabilities when searching for files, which can improve performance on projects with a large number of files.
例子:
json "fileFiltering": { "respectGitIgnore": true, "enableRecursiveFileSearch": false, "disableFuzzySearch": true }¥Example:
json "fileFiltering": { "respectGitIgnore": true, "enableRecursiveFileSearch": false, "disableFuzzySearch": true }
文件搜索性能故障排除
¥Troubleshooting File Search Performance
如果您在文件搜索时遇到性能问题(例如,@对于需要大量文件的项目(例如,许多已完成的文件),您可以尝试以下几项操作(按推荐顺序):
¥If you are experiencing performance issues with file searching (e.g., with @ completions), especially in projects with a very large number of files, here are a few things you can try in order of recommendation:
-
使用
.geminiignore:创建一个.geminiignore在项目根目录中删除包含大量不需要引用的文件的目录(例如,构建工件、日志、node_modules).减少抓取的文件总数是提高性能最有效的方法。¥Use
.geminiignore: Create a.geminiignorefile in your project root to exclude directories that contain a large number of files that you don't need to reference (e.g., build artifacts, logs,node_modules). Reducing the total number of files crawled is the most effective way to improve performance. -
禁用模糊搜索:如果忽略文件还不够,你可以通过设置禁用模糊搜索
disableFuzzySearch到true在你的settings.json文件。这将使用更简单、非模糊匹配算法,速度更快。¥Disable Fuzzy Search: If ignoring files is not enough, you can disable fuzzy search by setting
disableFuzzySearchtotruein yoursettings.jsonfile. This will use a simpler, non-fuzzy matching algorithm, which can be faster. -
禁用递归文件搜索:作为最后的手段,您可以通过设置完全禁用递归文件搜索
enableRecursiveFileSearch到false。这将是最快的选项,因为它避免了递归抓取你的项目。但是,这意味着在使用时你需要输入文件的完整路径@完成。¥Disable Recursive File Search: As a last resort, you can disable recursive file search entirely by setting
enableRecursiveFileSearchtofalse. This will be the fastest option as it avoids a recursive crawl of your project. However, it means you will need to type the full path to files when using@completions. -
coreTools(字符串数组):¥
coreTools(array of strings): 描述:允许您指定模型可用的核心工具名称列表。这可用于限制内置工具集。请参阅内置工具以获取核心工具列表。您还可以为支持该命令的工具指定特定于命令的限制,例如
ShellTool。 例如,"coreTools": ["ShellTool(ls -l)"]只允许ls -l要执行的命令。¥Description: Allows you to specify a list of core tool names that should be made available to the model. This can be used to restrict the set of built-in tools. See Built-in Tools for a list of core tools. You can also specify command-specific restrictions for tools that support it, like the
ShellTool. For example,"coreTools": ["ShellTool(ls -l)"]will only allow thels -lcommand to be executed.默认:所有可供 Gemini 模型使用的工具。
¥Default: All tools available for use by the Gemini model.
-
例子:
"coreTools": ["ReadFileTool", "GlobTool", "ShellTool(ls)"]。¥Example:
"coreTools": ["ReadFileTool", "GlobTool", "ShellTool(ls)"]. -
allowedTools(字符串数组):¥
allowedTools(array of strings): 默认:
undefined¥Default:
undefined描述:绕过确认对话框的工具名称列表。这对于您信任且经常使用的工具非常有用。匹配语义与
coreTools。¥Description: A list of tool names that will bypass the confirmation dialog. This is useful for tools that you trust and use frequently. The match semantics are the same as
coreTools.-
例子:
"allowedTools": ["ShellTool(git status)"]。¥Example:
"allowedTools": ["ShellTool(git status)"]. -
excludeTools(字符串数组):¥
excludeTools(array of strings): 描述:允许您指定应从模型中排除的核心工具名称列表。同时列出的工具
excludeTools和coreTools被排除。您还可以为支持该命令的工具指定特定于命令的限制,例如ShellTool。 例如,"excludeTools": ["ShellTool(rm -rf)"]将阻止rm -rf命令。¥Description: Allows you to specify a list of core tool names that should be excluded from the model. A tool listed in both
excludeToolsandcoreToolsis excluded. You can also specify command-specific restrictions for tools that support it, like theShellTool. For example,"excludeTools": ["ShellTool(rm -rf)"]will block therm -rfcommand.默认:不排除任何工具。
¥Default: No tools excluded.
例子:
"excludeTools": ["run_shell_command", "findFiles"]。¥Example:
"excludeTools": ["run_shell_command", "findFiles"].-
安全说明:命令特定的限制
excludeTools为了run_shell_command基于简单的字符串匹配,很容易被绕过。此功能不是安全机制不应依赖它来安全地执行不受信任的代码。建议使用coreTools明确选择可以执行的命令。¥Security Note: Command-specific restrictions in
excludeToolsforrun_shell_commandare based on simple string matching and can be easily bypassed. This feature is not a security mechanism and should not be relied upon to safely execute untrusted code. It is recommended to usecoreToolsto explicitly select commands that can be executed. -
allowMCPServers(字符串数组):¥
allowMCPServers(array of strings): 描述:允许您指定模型可用的 MCP 服务器名称列表。这可用于限制要连接的 MCP 服务器集合。请注意,如果
--allowed-mcp-server-names已设置。¥Description: Allows you to specify a list of MCP server names that should be made available to the model. This can be used to restrict the set of MCP servers to connect to. Note that this will be ignored if
--allowed-mcp-server-namesis set.默认:所有 MCP 服务器均可供 Gemini 模型使用。
¥Default: All MCP servers are available for use by the Gemini model.
例子:
"allowMCPServers": ["myPythonServer"]。¥Example:
"allowMCPServers": ["myPythonServer"].-
安全说明:此功能使用简单的字符串匹配 MCP 服务器名称,这些名称可以修改。如果您是系统管理员,希望防止用户绕过此功能,请考虑配置
mcpServers在系统设置层面,用户将无法配置任何自己的 MCP 服务器。这不应被用作一种严密的安全机制。¥Security Note: This uses simple string matching on MCP server names, which can be modified. If you're a system administrator looking to prevent users from bypassing this, consider configuring the
mcpServersat the system settings level such that the user will not be able to configure any MCP servers of their own. This should not be used as an airtight security mechanism. -
excludeMCPServers(字符串数组):¥
excludeMCPServers(array of strings): 描述:允许您指定应从模型中排除的 MCP 服务器名称列表。同时列出的服务器
excludeMCPServers和allowMCPServers被排除。请注意,如果--allowed-mcp-server-names已设置。¥Description: Allows you to specify a list of MCP server names that should be excluded from the model. A server listed in both
excludeMCPServersandallowMCPServersis excluded. Note that this will be ignored if--allowed-mcp-server-namesis set.默认:不排除任何 MCP 服务器。
¥Default: No MCP servers excluded.
例子:
"excludeMCPServers": ["myNodeServer"]。¥Example:
"excludeMCPServers": ["myNodeServer"].-
安全说明:此功能使用简单的字符串匹配 MCP 服务器名称,这些名称可以修改。如果您是系统管理员,希望防止用户绕过此功能,请考虑配置
mcpServers在系统设置层面,用户将无法配置任何自己的 MCP 服务器。这不应被用作一种严密的安全机制。¥Security Note: This uses simple string matching on MCP server names, which can be modified. If you're a system administrator looking to prevent users from bypassing this, consider configuring the
mcpServersat the system settings level such that the user will not be able to configure any MCP servers of their own. This should not be used as an airtight security mechanism. -
autoAccept(布尔值):¥
autoAccept(boolean): 描述:控制 CLI 是否自动接受并执行被认为安全的工具调用(例如,只读操作),而无需用户明确确认。如果设置为
true,CLI 将绕过被认为安全的工具的确认提示。¥Description: Controls whether the CLI automatically accepts and executes tool calls that are considered safe (e.g., read-only operations) without explicit user confirmation. If set to
true, the CLI will bypass the confirmation prompt for tools deemed safe.默认:
false¥Default:
false-
例子:
"autoAccept": true¥Example:
"autoAccept": true -
theme(细绳):¥
theme(string): 描述:设置视觉主题适用于 Gemini CLI。
¥Description: Sets the visual theme for Gemini CLI.
默认:
"Default"¥Default:
"Default"-
例子:
"theme": "GitHub"¥Example:
"theme": "GitHub" -
vimMode(布尔值):¥
vimMode(boolean): 描述:启用或禁用用于输入编辑的 Vim 模式。启用后,输入区域将支持 Vim 风格的导航和编辑命令,包括 NORMAL 和 INSERT 模式。Vim 模式状态显示在页脚中,并在会话之间持续显示。
¥Description: Enables or disables vim mode for input editing. When enabled, the input area supports vim-style navigation and editing commands with NORMAL and INSERT modes. The vim mode status is displayed in the footer and persists between sessions.
默认:
false¥Default:
false-
例子:
"vimMode": true¥Example:
"vimMode": true -
sandbox(布尔值或字符串):¥
sandbox(boolean or string): 描述:控制是否以及如何使用沙盒来执行工具。如果设置为
true,Gemini CLI 使用预建的gemini-cli-sandboxDocker 镜像。更多信息,请参阅沙盒。¥Description: Controls whether and how to use sandboxing for tool execution. If set to
true, Gemini CLI uses a pre-builtgemini-cli-sandboxDocker image. For more information, see Sandboxing.默认:
false¥Default:
false-
例子:
"sandbox": "docker"¥Example:
"sandbox": "docker" -
toolDiscoveryCommand(细绳):¥
toolDiscoveryCommand(string): 描述:定义一个自定义的 shell 命令,用于从项目中发现工具。shell 命令必须返回
stdoutJSON 数组函数声明. 工具包装器是可选的。¥Description: Defines a custom shell command for discovering tools from your project. The shell command must return on
stdouta JSON array of function declarations. Tool wrappers are optional.默认:空的
¥Default: Empty
-
例子:
"toolDiscoveryCommand": "bin/get_tools"¥Example:
"toolDiscoveryCommand": "bin/get_tools" -
toolCallCommand(细绳):¥
toolCallCommand(string): 描述:定义一个自定义 shell 命令,用于调用使用以下方式发现的特定工具
toolDiscoveryCommand。shell命令必须满足以下条件:¥Description: Defines a custom shell command for calling a specific tool that was discovered using
toolDiscoveryCommand. The shell command must meet the following criteria:它必须发挥作用
name(正如函数声明)作为第一个命令行参数。¥It must take function
name(exactly as in function declaration) as first command line argument.它必须将函数参数读取为 JSON
stdin,类似于functionCall.args。¥It must read function arguments as JSON on
stdin, analogous tofunctionCall.args.它必须以 JSON 形式返回函数输出
stdout,类似于functionResponse.response.content。¥It must return function output as JSON on
stdout, analogous tofunctionResponse.response.content.
默认:空的
¥Default: Empty
-
例子:
"toolCallCommand": "bin/call_tool"¥Example:
"toolCallCommand": "bin/call_tool" -
mcpServers(目的):¥
mcpServers(object): 描述:配置与一个或多个模型上下文协议 (MCP) 服务器的连接,以发现和使用自定义工具。Gemini CLI 会尝试连接到每个已配置的 MCP 服务器以发现可用的工具。如果多个 MCP 服务器公开同名工具,则工具名称将以您在配置中定义的服务器别名作为前缀(例如,
serverAlias__actualToolName) 以避免冲突。请注意,系统可能会从 MCP 工具定义中删除某些架构属性以实现兼容性。至少有一个command,url, 或者httpUrl必须提供。如果指定了多个,则优先顺序为httpUrl, 然后url, 然后command。¥Description: Configures connections to one or more Model-Context Protocol (MCP) servers for discovering and using custom tools. Gemini CLI attempts to connect to each configured MCP server to discover available tools. If multiple MCP servers expose a tool with the same name, the tool names will be prefixed with the server alias you defined in the configuration (e.g.,
serverAlias__actualToolName) to avoid conflicts. Note that the system might strip certain schema properties from MCP tool definitions for compatibility. At least one ofcommand,url, orhttpUrlmust be provided. If multiple are specified, the order of precedence ishttpUrl, thenurl, thencommand.默认:空的
¥Default: Empty
特性:
¥Properties:
<SERVER_NAME>(对象):指定服务器的服务器参数。¥
<SERVER_NAME>(object): The server parameters for the named server.command(字符串,可选):通过标准 I/O 启动 MCP 服务器时执行的命令。¥
command(string, optional): The command to execute to start the MCP server via standard I/O.args(字符串数组,可选):传递给命令的参数。¥
args(array of strings, optional): Arguments to pass to the command.env(对象,可选):为服务器进程设置的环境变量。¥
env(object, optional): Environment variables to set for the server process.cwd(字符串,可选):启动服务器的工作目录。¥
cwd(string, optional): The working directory in which to start the server.url(字符串,可选):使用服务器发送事件 (SSE) 进行通信的 MCP 服务器的 URL。¥
url(string, optional): The URL of an MCP server that uses Server-Sent Events (SSE) for communication.httpUrl(字符串,可选):使用可流式传输的 HTTP 进行通信的 MCP 服务器的 URL。¥
httpUrl(string, optional): The URL of an MCP server that uses streamable HTTP for communication.headers(对象,可选):与请求一起发送的 HTTP 标头映射url或者httpUrl。¥
headers(object, optional): A map of HTTP headers to send with requests tourlorhttpUrl.timeout(数字,可选):对此 MCP 服务器的请求超时时间(以毫秒为单位)。¥
timeout(number, optional): Timeout in milliseconds for requests to this MCP server.trust(布尔值,可选):信任此服务器并绕过所有工具调用确认。¥
trust(boolean, optional): Trust this server and bypass all tool call confirmations.description(字符串,可选):服务器的简要描述,可用于显示目的。¥
description(string, optional): A brief description of the server, which may be used for display purposes.includeTools(字符串数组,可选):要从此 MCP 服务器添加的工具名称列表。指定后,只有此处列出的工具可从此服务器使用(白名单行为)。如果未指定,则默认启用此服务器的所有工具。¥
includeTools(array of strings, optional): List of tool names to include from this MCP server. When specified, only the tools listed here will be available from this server (whitelist behavior). If not specified, all tools from the server are enabled by default.excludeTools(字符串数组,可选):要从此 MCP 服务器中排除的工具名称列表。此处列出的工具即使已由服务器公开,也不会对模型可用。笔记:excludeTools优先于includeTools- 如果某个工具同时出现在两个列表中,则它将被排除。¥
excludeTools(array of strings, optional): List of tool names to exclude from this MCP server. Tools listed here will not be available to the model, even if they are exposed by the server. Note:excludeToolstakes precedence overincludeTools- if a tool is in both lists, it will be excluded.
-
例子:
json "mcpServers": { "myPythonServer": { "command": "python", "args": ["mcp_server.py", "--port", "8080"], "cwd": "./mcp_tools/python", "timeout": 5000, "includeTools": ["safe_tool", "file_reader"], }, "myNodeServer": { "command": "node", "args": ["mcp_server.js"], "cwd": "./mcp_tools/node", "excludeTools": ["dangerous_tool", "file_deleter"] }, "myDockerServer": { "command": "docker", "args": ["run", "-i", "--rm", "-e", "API_KEY", "ghcr.io/foo/bar"], "env": { "API_KEY": "$MY_API_TOKEN" } }, "mySseServer": { "url": "http://localhost:8081/events", "headers": { "Authorization": "Bearer $MY_SSE_TOKEN" }, "description": "An example SSE-based MCP server." }, "myStreamableHttpServer": { "httpUrl": "http://localhost:8082/stream", "headers": { "X-API-Key": "$MY_HTTP_API_KEY" }, "description": "An example Streamable HTTP-based MCP server." } }¥Example:
json "mcpServers": { "myPythonServer": { "command": "python", "args": ["mcp_server.py", "--port", "8080"], "cwd": "./mcp_tools/python", "timeout": 5000, "includeTools": ["safe_tool", "file_reader"], }, "myNodeServer": { "command": "node", "args": ["mcp_server.js"], "cwd": "./mcp_tools/node", "excludeTools": ["dangerous_tool", "file_deleter"] }, "myDockerServer": { "command": "docker", "args": ["run", "-i", "--rm", "-e", "API_KEY", "ghcr.io/foo/bar"], "env": { "API_KEY": "$MY_API_TOKEN" } }, "mySseServer": { "url": "http://localhost:8081/events", "headers": { "Authorization": "Bearer $MY_SSE_TOKEN" }, "description": "An example SSE-based MCP server." }, "myStreamableHttpServer": { "httpUrl": "http://localhost:8082/stream", "headers": { "X-API-Key": "$MY_HTTP_API_KEY" }, "description": "An example Streamable HTTP-based MCP server." } } -
checkpointing(目的):¥
checkpointing(object): 描述:配置检查点功能,该功能允许您保存和恢复对话和文件状态。请参阅检查点文档了解更多详情。
¥Description: Configures the checkpointing feature, which allows you to save and restore conversation and file states. See the Checkpointing documentation for more details.
默认:
{"enabled": false}¥Default:
{"enabled": false}-
特性:
¥Properties:
enabled(布尔值): 当true, 这/restore命令可用。¥
enabled(boolean): Whentrue, the/restorecommand is available.
-
preferredEditor(细绳):¥
preferredEditor(string): 描述:指定用于查看差异的首选编辑器。
¥Description: Specifies the preferred editor to use for viewing diffs.
默认:
vscode¥Default:
vscode-
例子:
"preferredEditor": "vscode"¥Example:
"preferredEditor": "vscode" -
telemetry(目的)¥
telemetry(object) 描述:配置 Gemini CLI 的日志记录和指标收集。更多信息,请参阅遥测。
¥Description: Configures logging and metrics collection for Gemini CLI. For more information, see Telemetry.
默认:
{"enabled": false, "target": "local", "otlpEndpoint": "http://localhost:4317", "logPrompts": true}¥Default:
{"enabled": false, "target": "local", "otlpEndpoint": "http://localhost:4317", "logPrompts": true}特性:
¥Properties:
enabled(布尔值):是否启用遥测。¥
enabled(boolean): Whether or not telemetry is enabled.target(字符串):收集遥测数据的目的地。支持的值包括local和gcp。¥
target(string): The destination for collected telemetry. Supported values arelocalandgcp.otlpEndpoint(字符串):OTLP 导出器的端点。¥
otlpEndpoint(string): The endpoint for the OTLP Exporter.logPrompts(布尔值):是否在日志中包含用户提示的内容。¥
logPrompts(boolean): Whether or not to include the content of user prompts in the logs.
例子:
json "telemetry": { "enabled": true, "target": "local", "otlpEndpoint": "http://localhost:16686", "logPrompts": false }¥Example:
json "telemetry": { "enabled": true, "target": "local", "otlpEndpoint": "http://localhost:16686", "logPrompts": false }usageStatisticsEnabled(布尔值):¥
usageStatisticsEnabled(boolean):描述:启用或禁用使用情况统计信息的收集。请参阅使用情况统计了解更多信息。
¥Description: Enables or disables the collection of usage statistics. See Usage Statistics for more information.
默认:
true¥Default:
true-
例子:
json "usageStatisticsEnabled": false¥Example:
json "usageStatisticsEnabled": false -
hideTips(布尔值):¥
hideTips(boolean): 描述:启用或禁用 CLI 界面中的有用提示。
¥Description: Enables or disables helpful tips in the CLI interface.
默认:
false¥Default:
false-
例子:
¥Example:
json "hideTips": true¥
json "hideTips": true -
hideBanner(布尔值):¥
hideBanner(boolean): 描述:在 CLI 界面中启用或禁用启动横幅(ASCII 艺术徽标)。
¥Description: Enables or disables the startup banner (ASCII art logo) in the CLI interface.
默认:
false¥Default:
false-
例子:
¥Example:
json "hideBanner": true¥
json "hideBanner": true -
maxSessionTurns(数字):¥
maxSessionTurns(number): 描述:设置会话的最大轮次数。如果会话超出此限制,CLI 将停止处理并开始新的聊天。
¥Description: Sets the maximum number of turns for a session. If the session exceeds this limit, the CLI will stop processing and start a new chat.
默认:
-1(无限)¥Default:
-1(unlimited)-
例子:
json "maxSessionTurns": 10¥Example:
json "maxSessionTurns": 10 -
summarizeToolOutput(目的):¥
summarizeToolOutput(object): 描述:启用或禁用工具输出的汇总。您可以使用
tokenBudget环境。¥Description: Enables or disables the summarization of tool output. You can specify the token budget for the summarization using the
tokenBudgetsetting.注意:目前只有
run_shell_command工具受支持。¥Note: Currently only the
run_shell_commandtool is supported.默认:
{}(默认禁用)¥Default:
{}(Disabled by default)-
例子:
json "summarizeToolOutput": { "run_shell_command": { "tokenBudget": 2000 } }¥Example:
json "summarizeToolOutput": { "run_shell_command": { "tokenBudget": 2000 } } -
excludedProjectEnvVars(字符串数组):¥
excludedProjectEnvVars(array of strings): 描述:指定应从项目中排除加载的环境变量
.env文件。这可以防止项目特定的环境变量(例如DEBUG=true) 干扰 gemini-cli 的行为。变量来自.gemini/.env文件永远不会被排除。¥Description: Specifies environment variables that should be excluded from being loaded from project
.envfiles. This prevents project-specific environment variables (likeDEBUG=true) from interfering with gemini-cli behavior. Variables from.gemini/.envfiles are never excluded.默认:
["DEBUG", "DEBUG_MODE"]¥Default:
["DEBUG", "DEBUG_MODE"]-
例子:
json "excludedProjectEnvVars": ["DEBUG", "DEBUG_MODE", "NODE_ENV"]¥Example:
json "excludedProjectEnvVars": ["DEBUG", "DEBUG_MODE", "NODE_ENV"] -
includeDirectories(字符串数组):¥
includeDirectories(array of strings): 描述:指定要包含在工作区上下文中的额外绝对或相对路径数组。默认情况下,缺少的目录将被跳过并发出警告。路径可以使用
~引用用户的主目录。此设置可以与--include-directories命令行标志。¥Description: Specifies an array of additional absolute or relative paths to include in the workspace context. Missing directories will be skipped with a warning by default. Paths can use
~to refer to the user's home directory. This setting can be combined with the--include-directoriescommand-line flag.默认:
[]¥Default:
[]-
例子:
json "includeDirectories": [ "/path/to/another/project", "../shared-library", "~/common-utils" ]¥Example:
json "includeDirectories": [ "/path/to/another/project", "../shared-library", "~/common-utils" ] -
loadMemoryFromIncludeDirectories(布尔值):¥
loadMemoryFromIncludeDirectories(boolean): 描述:控制
/memory refresh命令。如果设置为true,GEMINI.md文件应该从所有添加的目录中加载。如果设置为false,GEMINI.md应该只从当前目录加载。¥Description: Controls the behavior of the
/memory refreshcommand. If set totrue,GEMINI.mdfiles should be loaded from all directories that are added. If set tofalse,GEMINI.mdshould only be loaded from the current directory.默认:
false¥Default:
false-
例子:
json "loadMemoryFromIncludeDirectories": true¥Example:
json "loadMemoryFromIncludeDirectories": true -
chatCompression(目的):¥
chatCompression(object): 描述:控制聊天历史压缩的设置,包括自动压缩和通过 /compress 命令手动调用的压缩。
¥Description: Controls the settings for chat history compression, both automatic and when manually invoked through the /compress command.
特性:
¥Properties:
contextPercentageThreshold(数字):介于 0 到 1 之间的值,用于指定压缩的令牌阈值,以占模型总令牌限制的百分比表示。例如,0.6当聊天记录超过令牌限制的60%时将触发压缩。¥
contextPercentageThreshold(number): A value between 0 and 1 that specifies the token threshold for compression as a percentage of the model's total token limit. For example, a value of0.6will trigger compression when the chat history exceeds 60% of the token limit.
-
例子:
json "chatCompression": { "contextPercentageThreshold": 0.6 }¥Example:
json "chatCompression": { "contextPercentageThreshold": 0.6 } -
showLineNumbers(布尔值):¥
showLineNumbers(boolean): 描述:控制 CLI 输出中的代码块中是否显示行号。
¥Description: Controls whether line numbers are displayed in code blocks in the CLI output.
默认:
true¥Default:
true-
例子:
json "showLineNumbers": false¥Example:
json "showLineNumbers": false -
accessibility(目的):¥
accessibility(object): 描述:配置 CLI 的辅助功能。
¥Description: Configures accessibility features for the CLI.
特性:
¥Properties:
screenReader(布尔值):启用屏幕阅读器模式,该模式可调整 TUI 以更好地兼容屏幕阅读器。也可以通过--screen-reader命令行标志,它将优先于设置。¥
screenReader(boolean): Enables screen reader mode, which adjusts the TUI for better compatibility with screen readers. This can also be enabled with the--screen-readercommand-line flag, which will take precedence over the setting.disableLoadingPhrases(布尔值):禁用操作期间加载短语的显示。¥
disableLoadingPhrases(boolean): Disables the display of loading phrases during operations.
默认:
{"screenReader": false, "disableLoadingPhrases": false}¥Default:
{"screenReader": false, "disableLoadingPhrases": false}例子:
json "accessibility": { "screenReader": true, "disableLoadingPhrases": true }¥Example:
json "accessibility": { "screenReader": true, "disableLoadingPhrases": true }
例子settings.json:
¥Example settings.json:
{
"theme": "GitHub",
"sandbox": "docker",
"toolDiscoveryCommand": "bin/get_tools",
"toolCallCommand": "bin/call_tool",
"mcpServers": {
"mainServer": {
"command": "bin/mcp_server.py"
},
"anotherServer": {
"command": "node",
"args": ["mcp_server.js", "--verbose"]
}
},
"telemetry": {
"enabled": true,
"target": "local",
"otlpEndpoint": "http://localhost:4317",
"logPrompts": true
},
"usageStatisticsEnabled": true,
"hideTips": false,
"hideBanner": false,
"maxSessionTurns": 10,
"summarizeToolOutput": {
"run_shell_command": {
"tokenBudget": 100
}
},
"excludedProjectEnvVars": ["DEBUG", "DEBUG_MODE", "NODE_ENV"],
"includeDirectories": ["path/to/dir1", "~/path/to/dir2", "../path/to/dir3"],
"loadMemoryFromIncludeDirectories": true
}
壳牌历史
¥Shell History
CLI 会保存您运行过的 shell 命令的历史记录。为了避免不同项目之间的冲突,这些历史记录存储在用户主文件夹中特定于项目的目录中。
¥The CLI keeps a history of shell commands you run. To avoid conflicts between different projects, this history is stored in a project-specific directory within your user's home folder.
地点:
~/.gemini/tmp/<project_hash>/shell_history¥Location:
~/.gemini/tmp/<project_hash>/shell_history<project_hash>是从项目根路径生成的唯一标识符。¥
<project_hash>is a unique identifier generated from your project's root path.历史记录存储在名为
shell_history。¥The history is stored in a file named
shell_history.
环境变量 &.env文件
¥Environment Variables & .env Files
环境变量是配置应用程序的常用方法,尤其适用于 API 密钥等敏感信息或可能在不同环境之间发生变化的设置。有关身份验证设置,请参阅身份验证文档涵盖所有可用的身份验证方法。
¥Environment variables are a common way to configure applications, especially for sensitive information like API keys or for settings that might change between environments. For authentication setup, see the Authentication documentation which covers all available authentication methods.
CLI 自动从.env文件。加载顺序为:
¥The CLI automatically loads environment variables from an .env file. The loading order is:
.env当前工作目录中的文件。¥
.envfile in the current working directory.如果未找到,它会在父目录中向上搜索,直到找到
.env文件或到达项目根目录(由.git文件夹)或主目录。¥If not found, it searches upwards in parent directories until it finds an
.envfile or reaches the project root (identified by a.gitfolder) or the home directory.如果仍未找到,它会查找
~/.env(在用户的主目录中)。¥If still not found, it looks for
~/.env(in the user's home directory).
环境变量排除:一些环境变量(如DEBUG和DEBUG_MODE) 将自动排除在项目加载之外.env文件以防止干扰 gemini-cli 的行为。变量来自.gemini/.env文件永远不会被排除。您可以使用excludedProjectEnvVars在您的设置中settings.json文件。
¥Environment Variable Exclusion: Some environment variables (like DEBUG and DEBUG_MODE) are automatically excluded from being loaded from project .env files to prevent interference with gemini-cli behavior. Variables from .gemini/.env files are never excluded. You can customize this behavior using the excludedProjectEnvVars setting in your settings.json file.
GEMINI_API_KEY:¥
GEMINI_API_KEY:您的 Gemini API 的 API 密钥。
¥Your API key for the Gemini API.
几种可用方法之一身份验证方法。
¥One of several available authentication methods.
在您的 shell 配置文件中设置此项(例如,
~/.bashrc,~/.zshrc)或.env文件。¥Set this in your shell profile (e.g.,
~/.bashrc,~/.zshrc) or an.envfile.GEMINI_MODEL:¥
GEMINI_MODEL:指定要使用的默认 Gemini 模型。
¥Specifies the default Gemini model to use.
覆盖硬编码默认值
¥Overrides the hardcoded default
例子:
export GEMINI_MODEL="gemini-2.5-flash"¥Example:
export GEMINI_MODEL="gemini-2.5-flash"GOOGLE_API_KEY:¥
GOOGLE_API_KEY:您的 Google Cloud API 密钥。
¥Your Google Cloud API key.
在快速模式下使用 Vertex AI 是必需的。
¥Required for using Vertex AI in express mode.
确保您拥有必要的权限。
¥Ensure you have the necessary permissions.
例子:
export GOOGLE_API_KEY="YOUR_GOOGLE_API_KEY"。¥Example:
export GOOGLE_API_KEY="YOUR_GOOGLE_API_KEY".GOOGLE_CLOUD_PROJECT:¥
GOOGLE_CLOUD_PROJECT:您的 Google Cloud 项目 ID。
¥Your Google Cloud Project ID.
使用 Code Assist 或 Vertex AI 时必需。
¥Required for using Code Assist or Vertex AI.
如果使用 Vertex AI,请确保您在该项目中拥有必要的权限。
¥If using Vertex AI, ensure you have the necessary permissions in this project.
Cloud Shell 注意事项:在 Cloud Shell 环境中运行时,此变量默认为分配给 Cloud Shell 用户的特殊项目。如果您有
GOOGLE_CLOUD_PROJECT在 Cloud Shell 的全局环境中设置,它将被此默认值覆盖。要在 Cloud Shell 中使用其他项目,您必须定义GOOGLE_CLOUD_PROJECT在一个.env文件。¥Cloud Shell Note: When running in a Cloud Shell environment, this variable defaults to a special project allocated for Cloud Shell users. If you have
GOOGLE_CLOUD_PROJECTset in your global environment in Cloud Shell, it will be overridden by this default. To use a different project in Cloud Shell, you must defineGOOGLE_CLOUD_PROJECTin a.envfile.例子:
export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"。¥Example:
export GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID".GOOGLE_APPLICATION_CREDENTIALS(细绳):¥
GOOGLE_APPLICATION_CREDENTIALS(string):描述:您的 Google 应用程序凭据 JSON 文件的路径。
¥Description: The path to your Google Application Credentials JSON file.
例子:
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/credentials.json"¥Example:
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/credentials.json"OTLP_GOOGLE_CLOUD_PROJECT:¥
OTLP_GOOGLE_CLOUD_PROJECT:您在 Google Cloud 中用于遥测的 Google Cloud 项目 ID
¥Your Google Cloud Project ID for Telemetry in Google Cloud
例子:
export OTLP_GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID"。¥Example:
export OTLP_GOOGLE_CLOUD_PROJECT="YOUR_PROJECT_ID".GOOGLE_CLOUD_LOCATION:¥
GOOGLE_CLOUD_LOCATION:您的 Google Cloud 项目位置(例如,us-central1)。
¥Your Google Cloud Project Location (e.g., us-central1).
在非快速模式下使用 Vertex AI 是必需的。
¥Required for using Vertex AI in non express mode.
例子:
export GOOGLE_CLOUD_LOCATION="YOUR_PROJECT_LOCATION"。¥Example:
export GOOGLE_CLOUD_LOCATION="YOUR_PROJECT_LOCATION".GEMINI_SANDBOX:¥
GEMINI_SANDBOX:替代
sandbox设置settings.json。¥Alternative to the
sandboxsetting insettings.json.接受
true,false,docker,podman或自定义命令字符串。¥Accepts
true,false,docker,podman, or a custom command string.SEATBELT_PROFILE(特定于 macOS):¥
SEATBELT_PROFILE(macOS specific):系好安全带(
sandbox-exec) macOS 上的配置文件。¥Switches the Seatbelt (
sandbox-exec) profile on macOS.permissive-open:(默认)限制写入项目文件夹(以及一些其他文件夹,请参阅packages/cli/src/utils/sandbox-macos-permissive-open.sb) 但允许其他操作。¥
permissive-open: (Default) Restricts writes to the project folder (and a few other folders, seepackages/cli/src/utils/sandbox-macos-permissive-open.sb) but allows other operations.strict:使用默认拒绝操作的严格配置文件。¥
strict: Uses a strict profile that declines operations by default.<profile_name>:使用自定义配置文件。要定义自定义配置文件,请创建一个名为sandbox-macos-<profile_name>.sb在你的项目中.gemini/目录(例如,my-project/.gemini/sandbox-macos-custom.sb)。¥
<profile_name>: Uses a custom profile. To define a custom profile, create a file namedsandbox-macos-<profile_name>.sbin your project's.gemini/directory (e.g.,my-project/.gemini/sandbox-macos-custom.sb).DEBUG或者DEBUG_MODE(通常由底层库或 CLI 本身使用):¥
DEBUGorDEBUG_MODE(often used by underlying libraries or the CLI itself):设置为
true或者1启用详细的调试日志记录,这有助于排除故障。¥Set to
trueor1to enable verbose debug logging, which can be helpful for troubleshooting.笔记:这些变量会自动从项目中排除
.env默认使用文件来防止干扰 gemini-cli 的行为。使用.gemini/.env如果您需要专门为 gemini-cli 设置这些文件。¥Note: These variables are automatically excluded from project
.envfiles by default to prevent interference with gemini-cli behavior. Use.gemini/.envfiles if you need to set these for gemini-cli specifically.NO_COLOR:¥
NO_COLOR:设置为任意值以禁用 CLI 中的所有颜色输出。
¥Set to any value to disable all color output in the CLI.
CLI_TITLE:¥
CLI_TITLE:设置为字符串以自定义 CLI 的标题。
¥Set to a string to customize the title of the CLI.
CODE_ASSIST_ENDPOINT:¥
CODE_ASSIST_ENDPOINT:指定代码辅助服务器的端点。
¥Specifies the endpoint for the code assist server.
这对于开发和测试很有用。
¥This is useful for development and testing.
命令行参数
¥Command-Line Arguments
运行 CLI 时直接传递的参数可以覆盖该特定会话的其他配置。
¥Arguments passed directly when running the CLI can override other configurations for that specific session.
--model <model_name>(-m <model_name>):¥
--model <model_name>(-m <model_name>):指定此会话要使用的 Gemini 模型。
¥Specifies the Gemini model to use for this session.
例子:
npm start -- --model gemini-1.5-pro-latest¥Example:
npm start -- --model gemini-1.5-pro-latest--prompt <your_prompt>(-p <your_prompt>):¥
--prompt <your_prompt>(-p <your_prompt>):用于将提示符直接传递给命令。这将以非交互模式调用 Gemini CLI。
¥Used to pass a prompt directly to the command. This invokes Gemini CLI in a non-interactive mode.
--prompt-interactive <your_prompt>(-i <your_prompt>):¥
--prompt-interactive <your_prompt>(-i <your_prompt>):以提供的提示作为初始输入来启动交互式会话。
¥Starts an interactive session with the provided prompt as the initial input.
提示是在交互式会话内处理的,而不是在它之前。
¥The prompt is processed within the interactive session, not before it.
从 stdin 管道输入时不能使用。
¥Cannot be used when piping input from stdin.
例子:
gemini -i "explain this code"¥Example:
gemini -i "explain this code"--sandbox(-s):¥
--sandbox(-s):为该会话启用沙盒模式。
¥Enables sandbox mode for this session.
--sandbox-image:¥
--sandbox-image:设置沙盒图像 URI。
¥Sets the sandbox image URI.
--debug(-d):¥
--debug(-d):为此会话启用调试模式,提供更详细的输出。
¥Enables debug mode for this session, providing more verbose output.
--all-files(-a):¥
--all-files(-a):如果设置,则以递归方式包含当前目录中的所有文件作为提示的上下文。
¥If set, recursively includes all files within the current directory as context for the prompt.
--help(或者-h):¥
--help(or-h):显示有关命令行参数的帮助信息。
¥Displays help information about command-line arguments.
--show-memory-usage:¥
--show-memory-usage:显示当前内存使用情况。
¥Displays the current memory usage.
--yolo:¥
--yolo:启用 YOLO 模式,自动批准所有工具调用。
¥Enables YOLO mode, which automatically approves all tool calls.
--approval-mode <mode>:¥
--approval-mode <mode>:设置工具调用的审批模式。可用模式:
¥Sets the approval mode for tool calls. Available modes:
default:每次工具调用时提示批准(默认行为)¥
default: Prompt for approval on each tool call (default behavior)auto_edit:自动批准编辑工具(replace、write_file),同时提示其他工具¥
auto_edit: Automatically approve edit tools (replace, write_file) while prompting for othersyolo:自动批准所有工具调用(相当于--yolo)¥
yolo: Automatically approve all tool calls (equivalent to--yolo)
不可与以下产品同时使用
--yolo。 使用--approval-mode=yolo而不是--yolo采取新的统一方法。¥Cannot be used together with
--yolo. Use--approval-mode=yoloinstead of--yolofor the new unified approach.例子:
gemini --approval-mode auto_edit¥Example:
gemini --approval-mode auto_edit--allowed-tools <tool1,tool2,...>:¥
--allowed-tools <tool1,tool2,...>:以逗号分隔的工具名称列表,将绕过确认对话框。
¥A comma-separated list of tool names that will bypass the confirmation dialog.
例子:
gemini --allowed-tools "ShellTool(git status)"¥Example:
gemini --allowed-tools "ShellTool(git status)"--telemetry:¥
--telemetry:启用遥测。
¥Enables telemetry.
--telemetry-target:¥
--telemetry-target:设置遥测目标。请参阅遥测了解更多信息。
¥Sets the telemetry target. See telemetry for more information.
--telemetry-otlp-endpoint:¥
--telemetry-otlp-endpoint:设置遥测的 OTLP 端点。请参阅遥测了解更多信息。
¥Sets the OTLP endpoint for telemetry. See telemetry for more information.
--telemetry-otlp-protocol:¥
--telemetry-otlp-protocol:设置遥测的 OTLP 协议(
grpc或者http)。默认为grpc。 看遥测了解更多信息。¥Sets the OTLP protocol for telemetry (
grpcorhttp). Defaults togrpc. See telemetry for more information.--telemetry-log-prompts:¥
--telemetry-log-prompts:启用遥测提示记录。请参阅遥测了解更多信息。
¥Enables logging of prompts for telemetry. See telemetry for more information.
--checkpointing:¥
--checkpointing:启用检查点。
¥Enables checkpointing.
--extensions <extension_name ...>(-e <extension_name ...>):¥
--extensions <extension_name ...>(-e <extension_name ...>):指定会话要使用的扩展列表。如果未提供,则使用所有可用的扩展。
¥Specifies a list of extensions to use for the session. If not provided, all available extensions are used.
使用特殊术语
gemini -e none禁用所有扩展。¥Use the special term
gemini -e noneto disable all extensions.例子:
gemini -e my-extension -e my-other-extension¥Example:
gemini -e my-extension -e my-other-extension--list-extensions(-l):¥
--list-extensions(-l):列出所有可用的扩展和出口。
¥Lists all available extensions and exits.
--proxy:¥
--proxy:设置 CLI 的代理。
¥Sets the proxy for the CLI.
例子:
--proxy http://localhost:7890。¥Example:
--proxy http://localhost:7890.--include-directories <dir1,dir2,...>:¥
--include-directories <dir1,dir2,...>:在工作区中包含额外的目录以实现多目录支持。
¥Includes additional directories in the workspace for multi-directory support.
可以多次指定或以逗号分隔的值指定。
¥Can be specified multiple times or as comma-separated values.
最多可添加5个目录。
¥5 directories can be added at maximum.
例子:
--include-directories /path/to/project1,/path/to/project2或者--include-directories /path/to/project1 --include-directories /path/to/project2¥Example:
--include-directories /path/to/project1,/path/to/project2or--include-directories /path/to/project1 --include-directories /path/to/project2--screen-reader:¥
--screen-reader:启用屏幕阅读器模式以实现无障碍功能。
¥Enables screen reader mode for accessibility.
--version:¥
--version:显示 CLI 的版本。
¥Displays the version of the CLI.
上下文文件(分层教学上下文)
¥Context Files (Hierarchical Instructional Context)
虽然不是严格配置 CLI 的行为、上下文文件(默认为GEMINI.md但可以通过contextFileName设置)对于配置教学背景(也称为“内存”)提供给 Gemini 模型。这项强大的功能允许您向 AI 提供项目特定的指令、编码风格指南或任何相关的背景信息,使其响应更加个性化和准确,以满足您的需求。CLI 包含一些 UI 元素,例如页脚中显示已加载上下文文件数量的指示器,可让您随时了解活动上下文。
¥While not strictly configuration for the CLI's behavior, context files (defaulting to GEMINI.md but configurable via the contextFileName setting) are crucial for configuring the instructional context (also referred to as "memory") provided to the Gemini model. This powerful feature allows you to give project-specific instructions, coding style guides, or any relevant background information to the AI, making its responses more tailored and accurate to your needs. The CLI includes UI elements, such as an indicator in the footer showing the number of loaded context files, to keep you informed about the active context.
目的:这些 Markdown 文件包含您希望 Gemini 模型在交互过程中感知到的说明、指南或上下文。系统旨在分层管理这些说明性上下文。
¥Purpose: These Markdown files contain instructions, guidelines, or context that you want the Gemini model to be aware of during your interactions. The system is designed to manage this instructional context hierarchically.
上下文文件内容示例(例如,GEMINI.md)
¥Example Context File Content (e.g., GEMINI.md)
以下是 TypeScript 项目根目录下的上下文文件可能包含的内容的概念示例:
¥Here's a conceptual example of what a context file at the root of a TypeScript project might contain:
# Project: My Awesome TypeScript Library
## General Instructions:
- When generating new TypeScript code, please follow the existing coding style.
- Ensure all new functions and classes have JSDoc comments.
- Prefer functional programming paradigms where appropriate.
- All code should be compatible with TypeScript 5.0 and Node.js 20+.
## Coding Style:
- Use 2 spaces for indentation.
- Interface names should be prefixed with `I` (e.g., `IUserService`).
- Private class members should be prefixed with an underscore (`_`).
- Always use strict equality (`===` and `!==`).
## Specific Component: `src/api/client.ts`
- This file handles all outbound API requests.
- When adding new API call functions, ensure they include robust error handling and logging.
- Use the existing `fetchWithRetry` utility for all GET requests.
## Regarding Dependencies:
- Avoid introducing new external dependencies unless absolutely necessary.
- If a new dependency is required, please state the reason.
此示例演示了如何提供通用的项目上下文、具体的编码约定,甚至关于特定文件或组件的注释。上下文文件越相关、越精确,AI 就能更好地为您提供帮助。强烈建议使用特定于项目的上下文文件来建立约定和上下文。
¥This example demonstrates how you can provide general project context, specific coding conventions, and even notes about particular files or components. The more relevant and precise your context files are, the better the AI can assist you. Project-specific context files are highly encouraged to establish conventions and context.
分层加载和优先级:CLI 通过加载上下文文件(例如,
GEMINI.md) 来自多个位置。此列表中较低位置的文件(更具体)的内容通常会覆盖或补充较高位置的文件(更通用)的内容。确切的连接顺序和最终上下文可以使用/memory show命令。典型的加载顺序是:¥Hierarchical Loading and Precedence: The CLI implements a sophisticated hierarchical memory system by loading context files (e.g.,
GEMINI.md) from several locations. Content from files lower in this list (more specific) typically overrides or supplements content from files higher up (more general). The exact concatenation order and final context can be inspected using the/memory showcommand. The typical loading order is:全局上下文文件:
¥Global Context File:
地点:
~/.gemini/<contextFileName>(例如,~/.gemini/GEMINI.md在您的用户主目录中)。¥Location:
~/.gemini/<contextFileName>(e.g.,~/.gemini/GEMINI.mdin your user home directory).范围:为您的所有项目提供默认说明。
¥Scope: Provides default instructions for all your projects.
项目根目录和祖先上下文文件:
¥Project Root & Ancestors Context Files:
位置:CLI 在当前工作目录中搜索配置的上下文文件,然后在每个父目录中搜索,直到项目根目录(由
.git文件夹)或您的主目录。¥Location: The CLI searches for the configured context file in the current working directory and then in each parent directory up to either the project root (identified by a
.gitfolder) or your home directory.范围:提供与整个项目或其重要部分相关的背景。
¥Scope: Provides context relevant to the entire project or a significant portion of it.
子目录上下文文件(上下文/本地):
¥Sub-directory Context Files (Contextual/Local):
位置:CLI 还会扫描子目录中配置的上下文文件以下当前工作目录(遵循常见的忽略模式,例如
node_modules,.git等)。默认情况下,此搜索范围限制为 200 个目录,但可以配置memoryDiscoveryMaxDirs你的领域settings.json文件。¥Location: The CLI also scans for the configured context file in subdirectories below the current working directory (respecting common ignore patterns like
node_modules,.git, etc.). The breadth of this search is limited to 200 directories by default, but can be configured with amemoryDiscoveryMaxDirsfield in yoursettings.jsonfile.范围:允许与项目的特定组件、模块或子部分相关的高度具体的指令。
¥Scope: Allows for highly specific instructions relevant to a particular component, module, or subsection of your project.
连接和 UI 指示:所有找到的上下文文件的内容都会被连接起来(使用分隔符指示其来源和路径),并作为系统提示的一部分提供给 Gemini 模型。CLI 页脚会显示已加载上下文文件的数量,让您快速直观地了解当前正在使用的教学上下文。
¥Concatenation & UI Indication: The contents of all found context files are concatenated (with separators indicating their origin and path) and provided as part of the system prompt to the Gemini model. The CLI footer displays the count of loaded context files, giving you a quick visual cue about the active instructional context.
导入内容:您可以通过使用导入其他 Markdown 文件来模块化您的上下文文件
@path/to/file.md语法。有关更多详细信息,请参阅内存导入处理器文档。¥Importing Content: You can modularize your context files by importing other Markdown files using the
@path/to/file.mdsyntax. For more details, see the Memory Import Processor documentation.内存管理命令:
¥Commands for Memory Management:
使用
/memory refresh强制重新扫描并加载所有配置位置的所有上下文文件。这将更新AI的教学上下文。¥Use
/memory refreshto force a re-scan and reload of all context files from all configured locations. This updates the AI's instructional context.使用
/memory show显示当前加载的组合教学内容,让您验证 AI 正在使用的层次结构和内容。¥Use
/memory showto display the combined instructional context currently loaded, allowing you to verify the hierarchy and content being used by the AI.查看命令文档了解详情
/memory命令及其子命令(show和refresh)。¥See the Commands documentation for full details on the
/memorycommand and its sub-commands (showandrefresh).
通过理解和利用这些配置层和上下文文件的层次性质,您可以有效地管理 AI 的内存并根据您的特定需求和项目定制 Gemini CLI 的响应。
¥By understanding and utilizing these configuration layers and the hierarchical nature of context files, you can effectively manage the AI's memory and tailor the Gemini CLI's responses to your specific needs and projects.
沙盒
¥Sandboxing
Gemini CLI 可以在沙盒环境中执行潜在的不安全操作(如 shell 命令和文件修改)以保护您的系统。
¥The Gemini CLI can execute potentially unsafe operations (like shell commands and file modifications) within a sandboxed environment to protect your system.
沙盒默认处于禁用状态,但您可以通过以下几种方式启用它:
¥Sandboxing is disabled by default, but you can enable it in a few ways:
使用
--sandbox或者-s旗帜。¥Using
--sandboxor-sflag.环境
GEMINI_SANDBOX环境变量。¥Setting
GEMINI_SANDBOXenvironment variable.使用时启用沙盒
--yolo或者--approval-mode=yolo默认情况下。¥Sandbox is enabled when using
--yoloor--approval-mode=yoloby default.
默认情况下,它使用预建的gemini-cli-sandboxDocker 镜像。
¥By default, it uses a pre-built gemini-cli-sandbox Docker image.
对于特定于项目的沙盒需求,您可以在以下位置创建自定义 Dockerfile.gemini/sandbox.Dockerfile位于项目的根目录中。此 Dockerfile 可以基于基础沙盒镜像:
¥For project-specific sandboxing needs, you can create a custom Dockerfile at .gemini/sandbox.Dockerfile in your project's root directory. This Dockerfile can be based on the base sandbox image:
FROM gemini-cli-sandbox
# Add your custom dependencies or configurations here
# For example:
# RUN apt-get update && apt-get install -y some-package
# COPY ./my-config /app/my-config
什么时候.gemini/sandbox.Dockerfile存在,你可以使用BUILD_SANDBOX运行 Gemini CLI 时的环境变量以自动构建自定义沙盒镜像:
¥When .gemini/sandbox.Dockerfile exists, you can use BUILD_SANDBOX environment variable when running Gemini CLI to automatically build the custom sandbox image:
BUILD_SANDBOX=1 gemini -s
使用情况统计
¥Usage Statistics
为了帮助我们改进 Gemini CLI,我们收集了匿名使用情况统计信息。这些数据有助于我们了解 CLI 的使用情况、发现常见问题并确定新功能的优先级。
¥To help us improve the Gemini CLI, we collect anonymized usage statistics. This data helps us understand how the CLI is used, identify common issues, and prioritize new features.
我们收集的信息:
¥What we collect:
工具调用:我们会记录所调用工具的名称、执行成功与否以及执行时长。我们不会收集传递给工具的参数或工具返回的任何数据。
¥Tool Calls: We log the names of the tools that are called, whether they succeed or fail, and how long they take to execute. We do not collect the arguments passed to the tools or any data returned by them.
API 请求:我们会记录每个请求所使用的 Gemini 模型、请求时长以及请求是否成功。我们不会收集提示或响应的内容。
¥API Requests: We log the Gemini model used for each request, the duration of the request, and whether it was successful. We do not collect the content of the prompts or responses.
会话信息:我们收集有关 CLI 配置的信息,例如启用的工具和批准模式。
¥Session Information: We collect information about the configuration of the CLI, such as the enabled tools and the approval mode.
我们不收集的信息:
¥What we DON'T collect:
个人身份信息 (PII):我们不会收集任何个人信息,例如您的姓名、电子邮件地址或 API 密钥。
¥Personally Identifiable Information (PII): We do not collect any personal information, such as your name, email address, or API keys.
提示和响应内容:我们不会记录您的提示内容或来自 Gemini 模型的响应。
¥Prompt and Response Content: We do not log the content of your prompts or the responses from the Gemini model.
文件内容:我们不会记录 CLI 读取或写入的任何文件的内容。
¥File Content: We do not log the content of any files that are read or written by the CLI.
如何选择退出:
¥How to opt out:
您可以随时通过设置退出使用情况统计信息收集usageStatisticsEnabled财产false在你的settings.json文件:
¥You can opt out of usage statistics collection at any time by setting the usageStatisticsEnabled property to false in your settings.json file:
{
"usageStatisticsEnabled": false
}