Files
wehub-resource-sync e5aef55c8b
Codespell / Check for spelling errors (push) Waiting to run
Lint and Test / lint_test (3.10) (push) Waiting to run
Lint and Test / lint_test (3.11) (push) Waiting to run
Lint and Test / lint_test (3.12) (push) Waiting to run
docs: make Chinese README the default
2026-07-13 10:47:44 +00:00

491 lines
26 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!-- WEHUB_ZH_README -->
> [!NOTE]
> 本文档由 WeHub 基于上游 README 翻译整理,属于社区翻译,非官方中文文档。
> [English](./README.en.md) · [原始项目](https://github.com/TheR1D/shell_gpt) · [上游 README](https://github.com/TheR1D/shell_gpt/blob/HEAD/README.md)
> 原作者、版权与许可证归属以原始项目及本仓库 LICENSE 文件为准。
# ShellGPT
一款由 AI 大语言模型(LLM)驱动的命令行生产力工具。该命令行工具可高效生成 **shell 命令、代码片段、文档**,无需借助外部资源(如 Google 搜索)。支持 Linux、macOS、Windows,并兼容 PowerShell、CMD、Bash、Zsh 等所有主流 Shell。
https://github.com/TheR1D/shell_gpt/assets/16740832/721ddb19-97e7-428f-a0ee-107d027ddd59
## 安装
```shell
pip install shell-gpt
```
默认情况下,ShellGPT 使用 OpenAI 的 API 和 GPT-4 模型。你需要一个 API 密钥,可以在[此处](https://platform.openai.com/api-keys). 生成。系统会提示你输入密钥,随后将保存在 `~/.config/shell_gpt/.sgptrc` 中。OpenAI API 并非免费,请参阅 [OpenAI 定价](https://openai.com/pricing) 了解更多信息。
> [!TIP]
> 或者,你也可以在本地免费运行开源模型。这需要搭建你自己的 LLM 后端,例如 [Ollama](https://github.com/ollama/ollama).。要让 ShellGPT 与 Ollama 配合使用,请按照这份详细的[指南](https://github.com/TheR1D/shell_gpt/wiki/Ollama) 操作。
>
> **❗️请注意,ShellGPT 并未针对本地模型进行优化,可能无法按预期工作。**
## 用法
**ShellGPT** 旨在快速分析和检索信息。它适用于从技术配置到一般常识的各类简单请求。
```shell
sgpt "What is the fibonacci sequence"
# -> The Fibonacci sequence is a series of numbers where each number ...
```
ShellGPT 可同时接受来自 stdin 和命令行参数的提示。无论你希望通过终端管道传入输入,还是直接以参数指定,`sgpt` 都能满足需求。例如,你可以根据 diff 轻松生成 git 提交信息:
```shell
git diff | sgpt "Generate git commit message, for my changes"
# -> Added main feature details into README.md
```
你还可以通过 stdin 传入日志并附带提示,从而分析来自各种来源的日志。例如,我们可以用它来快速分析日志、识别错误,并获取可能的解决方案建议:
```shell
docker logs -n 20 my_app | sgpt "check logs, find errors, provide possible solutions"
```
```text
Error Detected: Connection timeout at line 7.
Possible Solution: Check network connectivity and firewall settings.
Error Detected: Memory allocation failed at line 12.
Possible Solution: Consider increasing memory allocation or optimizing application memory usage.
```
你也可以使用各种重定向运算符来传入输入:
```shell
sgpt "summarise" < document.txt
# -> The document discusses the impact...
sgpt << EOF
What is the best way to lear Golang?
Provide simple hello world example.
EOF
# -> The best way to learn Golang...
sgpt <<< "What is the best way to learn shell redirects?"
# -> The best way to learn shell redirects is through...
```
### Shell 命令
你是否遇到过忘记常用 shell 命令(例如 `find`)而需要上网查询语法的情况?借助 `--shell` 或快捷选项 `-s`,你可以在终端中快速生成并执行所需命令。
```shell
sgpt --shell "find all json files in current folder"
# -> find . -type f -name "*.json"
# -> [E]xecute, [D]escribe, [A]bort: e
```
Shell GPT 会识别你所使用的操作系统和 `$SHELL`,并针对你的具体系统提供 shell 命令。例如,如果你让 `sgpt` 更新系统,它将根据你的操作系统返回相应命令。以下是在 macOS 上的示例:
```shell
sgpt -s "update my system"
# -> sudo softwareupdate -i -a
# -> [E]xecute, [D]escribe, [A]bort: e
```
同样的提示在 Ubuntu 上使用会生成不同的建议:
```shell
sgpt -s "update my system"
# -> sudo apt update && sudo apt upgrade -y
# -> [E]xecute, [D]escribe, [A]bort: e
```
让我们在 Docker 上试试看:
```shell
sgpt -s "start nginx container, mount ./index.html"
# -> docker run -d -p 80:80 -v $(pwd)/index.html:/usr/share/nginx/html/index.html nginx
# -> [E]xecute, [D]escribe, [A]bort: e
```
我们仍可通过管道将输入传给 `sgpt` 以生成 shell 命令:
```shell
sgpt -s "POST localhost with" < data.json
# -> curl -X POST -H "Content-Type: application/json" -d '{"a": 1, "b": 2}' http://localhost
# -> [E]xecute, [D]escribe, [A]bort: e
```
在提示中运用更多 shell 技巧,本例将文件名传给 `ffmpeg`
```shell
ls
# -> 1.mp4 2.mp4 3.mp4
sgpt -s "ffmpeg combine $(ls -m) into one video file without audio."
# -> ffmpeg -i 1.mp4 -i 2.mp4 -i 3.mp4 -filter_complex "[0:v] [1:v] [2:v] concat=n=3:v=1 [v]" -map "[v]" out.mp4
# -> [E]xecute, [D]escribe, [A]bort: e
```
如果你想通过管道传递生成的 shell 命令,可以使用 `--no-interaction` 选项。这将禁用交互模式,并将生成的命令输出到 stdout。在本例中,我们使用 `pbcopy` 将生成的命令复制到剪贴板:
```shell
sgpt -s "find all json files in current folder" --no-interaction | pbcopy
```
### Shell 集成
这是一项**非常实用的功能**,让你可以直接在终端中使用 `sgpt` shell 补全,而无需键入带提示和参数的 `sgpt`。Shell 集成支持在终端中通过热键使用 ShellGPT,Bash 和 ZSH 均支持。该功能会将 `sgpt` 补全直接放入终端缓冲区(输入行),便于立即编辑建议的命令。
https://github.com/TheR1D/shell_gpt/assets/16740832/bead0dab-0dd9-436d-88b7-6abfb2c556c1
要安装 shell 集成,请运行 `sgpt --install-integration` 并重启终端以应用更改。这会在你的 `.bashrc``.zshrc` 文件中添加几行配置。之后,你可以使用 `Ctrl+l`(默认)调用 ShellGPT。按下 `Ctrl+l` 时,它会用建议的命令替换你当前的输入行(缓冲区)。你可以随后编辑并按 `Enter` 执行。
### 生成代码
使用 `--code``-c` 参数,你可以专门请求纯代码输出,例如:
```shell
sgpt --code "solve fizz buzz problem using python"
```
```python
for i in range(1, 101):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
```
由于这是有效的 python 代码,我们可以将输出重定向到文件:
```shell
sgpt --code "solve classic fizz buzz problem using Python" > fizz_buzz.py
python fizz_buzz.py
# 1
# 2
# Fizz
# 4
# Buzz
# ...
```
我们也可以使用管道传入输入:
```shell
cat fizz_buzz.py | sgpt --code "Generate comments for each line of my code"
```
```python
# Loop through numbers 1 to 100
for i in range(1, 101):
# Check if number is divisible by both 3 and 5
if i % 3 == 0 and i % 5 == 0:
# Print "FizzBuzz" if number is divisible by both 3 and 5
print("FizzBuzz")
# Check if number is divisible by 3
elif i % 3 == 0:
# Print "Fizz" if number is divisible by 3
print("Fizz")
# Check if number is divisible by 5
elif i % 5 == 0:
# Print "Buzz" if number is divisible by 5
print("Buzz")
# If number is not divisible by 3 or 5, print the number itself
else:
print(i)
```
### 聊天模式
通常,保留并回忆对话很重要。`sgpt` 会在每次请求的 LLM 补全中创建对话式交流。对话可以逐条展开(chat mode,聊天模式)或在 REPL 循环中交互进行(REPL mode,REPL 模式)。两种方式都依赖同一个底层对象,称为 chat session(聊天会话)。该会话位于[可配置的](#runtime-configuration-file) `CHAT_CACHE_PATH`
要开始对话,请使用 `--chat` 选项,后跟唯一的会话名称和提示。
```shell
sgpt --chat conversation_1 "please remember my favorite number: 4"
# -> I will remember that your favorite number is 4.
sgpt --chat conversation_1 "what would be my favorite number + 4?"
# -> Your favorite number is 4, so if we add 4 to it, the result would be 8.
```
你可以通过 chat session(聊天会话)不断补充细节,迭代改进 GPT 的建议。可使用 `--code``--shell` 选项来启动 `--chat`
```shell
sgpt --chat conversation_2 --code "make a request to localhost using python"
```
```python
import requests
response = requests.get('http://localhost')
print(response.text)
```
为请求添加缓存,可以这样让 LLM 来做:
```shell
sgpt --chat conversation_2 --code "add caching"
```
```python
import requests
from cachecontrol import CacheControl
sess = requests.session()
cached_sess = CacheControl(sess)
response = cached_sess.get('http://localhost')
print(response.text)
```
Shell 命令同样适用:
```shell
sgpt --chat conversation_3 --shell "what is in current folder"
# -> ls
sgpt --chat conversation_3 "Sort by name"
# -> ls | sort
sgpt --chat conversation_3 "Concatenate them using FFMPEG"
# -> ffmpeg -i "concat:$(ls | sort | tr '\n' '|')" -codec copy output.mp4
sgpt --chat conversation_3 "Convert the resulting file into an MP3"
# -> ffmpeg -i output.mp4 -vn -acodec libmp3lame -ac 2 -ab 160k -ar 48000 final_output.mp3
```
要列出任一对话模式下的所有会话,请使用 `--list-chats``-lc` 选项:
```shell
sgpt --list-chats
# .../shell_gpt/chat_cache/conversation_1
# .../shell_gpt/chat_cache/conversation_2
```
要查看某个会话的全部消息,请使用 `--show-chat` 选项,后跟会话名称:
```shell
sgpt --show-chat conversation_1
# user: please remember my favorite number: 4
# assistant: I will remember that your favorite number is 4.
# user: what would be my favorite number + 4?
# assistant: Your favorite number is 4, so if we add 4 to it, the result would be 8.
```
### REPL 模式
有一种非常方便的 REPLreadevalprint loop,读-求值-输出循环)模式,可让你与 GPT 模型进行交互式对话。要在 REPL 模式下启动聊天会话,请使用 `--repl` 选项,后跟唯一的会话名称。你也可以使用 "temp" 作为会话名称来启动临时 REPL 会话。请注意,`--chat``--repl` 使用相同的底层对象,因此你可以用 `--chat` 启动聊天会话,再用 `--repl` 在 REPL 模式下继续该对话。
<p align="center">
<img src="https://s10.gifyu.com/images/repl-demo.gif" alt="gif">
</p>
```text
sgpt --repl temp
Entering REPL mode, press Ctrl+C to exit.
>>> What is REPL?
REPL stands for Read-Eval-Print Loop. It is a programming environment ...
>>> How can I use Python with REPL?
To use Python with REPL, you can simply open a terminal or command prompt ...
```
REPL 模式可与 `--shell``--code` 选项配合使用,非常适合交互式 shell 命令与代码生成:
```text
sgpt --repl temp --shell
Entering shell REPL mode, type [e] to execute commands or press Ctrl+C to exit.
>>> What is in current folder?
ls
>>> Show file sizes
ls -lh
>>> Sort them by file sizes
ls -lhS
>>> e (enter just e to execute commands, or d to describe them)
```
要提供多行提示,请使用三引号 `"""`
```text
sgpt --repl temp
Entering REPL mode, press Ctrl+C to exit.
>>> """
... Explain following code:
... import random
... print(random.randint(1, 10))
... """
It is a Python script that uses the random module to generate and print a random integer.
```
你也可以通过参数、stdin 或同时使用两者传入初始提示来进入 REPL 模式:
```shell
sgpt --repl temp < my_app.py
```
```text
Entering REPL mode, press Ctrl+C to exit.
──────────────────────────────────── Input ────────────────────────────────────
name = input("What is your name?")
print(f"Hello {name}")
───────────────────────────────────────────────────────────────────────────────
>>> What is this code about?
The snippet of code you've provided is written in Python. It prompts the user...
>>> Follow up questions...
```
### Function calling(函数调用)
[Function calls](https://platform.openai.com/docs/guides/function-calling) 是 OpenAI 提供的一项强大功能。它允许 LLM 在你的系统中执行函数,可用于完成各种任务。要安装 [default functions](https://github.com/TheR1D/shell_gpt/tree/main/sgpt/llm_functions/),请运行:
```shell
sgpt --install-functions
```
ShellGPT 提供了便捷的方式来定义和使用函数。要创建自定义函数,请进入 `~/.config/shell_gpt/functions`,并以函数名新建一个 .py 文件。在该文件中,可参考此 [example](https://github.com/TheR1D/shell_gpt/blob/main/sgpt/llm_functions/common/execute_shell.py). 来定义你的函数。
类内的 docstring 注释会连同 `title` 属性及参数说明一起,作为函数描述传给 OpenAI API。若 LLM 决定使用你的函数,则会调用 `execute` 函数。此处我们允许 LLM 在系统中执行任意 Shell 命令。由于我们会返回命令输出,LLM 可以分析该输出并判断是否适合当前提示。以下是 LLM 可能如何执行该函数的示例:
```shell
sgpt "What are the files in /tmp folder?"
# -> @FunctionCall execute_shell_command(shell_command="ls /tmp")
# -> The /tmp folder contains the following files and directories:
# -> test.txt
# -> test.json
```
请注意,若函数 (execute_shell_command) 因某种原因返回错误,LLM 仍可能根据输出尝试完成任务。假设系统中未安装 `jq`,而我们让 LLM 解析 JSON 文件:
```shell
sgpt "parse /tmp/test.json file using jq and return only email value"
# -> @FunctionCall execute_shell_command(shell_command="jq -r '.email' /tmp/test.json")
# -> It appears that jq is not installed on the system. Let me try to install it using brew.
# -> @FunctionCall execute_shell_command(shell_command="brew install jq")
# -> jq has been successfully installed. Let me try to parse the file again.
# -> @FunctionCall execute_shell_command(shell_command="jq -r '.email' /tmp/test.json")
# -> The email value in /tmp/test.json is johndoe@example.
```
也可以在提示中串联多次 function call(函数调用):
```shell
sgpt "Play music and open hacker news"
# -> @FunctionCall play_music()
# -> @FunctionCall open_url(url="https://news.ycombinator.com")
# -> Music is now playing, and Hacker News has been opened in your browser. Enjoy!
```
这只是 function call 用法的简单示例。它确实是一项强大功能,可完成各种复杂任务。我们在 GitHub Discussions 设有专门的 [category](https://github.com/TheR1D/shell_gpt/discussions/categories/functions),用于分享和讨论函数。
LLM 可能执行具有破坏性的命令,请自行承担风险❗️
### Roles(角色)
ShellGPT 允许你创建自定义角色,可用于生成代码、shell 命令或满足你的特定需求。要创建新角色,请使用 `--create-role` 选项,后跟角色名称。系统会提示你提供角色描述及其他详细信息。这将在 `~/.config/shell_gpt/roles` 中创建一个以角色名命名的 JSON 文件。在该目录中,你也可以编辑默认的 `sgpt` 角色,例如 **shell**、**code** 和 **default**。使用 `--list-roles` 选项可列出所有可用角色,使用 `--show-role` 选项可查看特定角色的详情。以下是自定义角色示例:
```shell
sgpt --create-role json_generator
# Enter role description: Provide only valid json as response.
sgpt --role json_generator "random: user, password, email, address"
```
```json
{
"user": "JohnDoe",
"password": "p@ssw0rd",
"email": "johndoe@example.com",
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": "12345"
}
}
```
若角色描述中包含 "APPLY MARKDOWN"(区分大小写),则聊天内容将使用 Markdown 格式显示,除非通过 `--no-md` 显式关闭。
### 请求缓存
使用 `--cache`(默认)和 `--no-cache` 选项来控制缓存。此缓存适用于所有发往 OpenAI API 的 `sgpt` 请求:
```shell
sgpt "what are the colors of a rainbow"
# -> The colors of a rainbow are red, orange, yellow, green, blue, indigo, and violet.
```
下次遇到完全相同的查询时,将立即从本地缓存获取结果。请注意,`sgpt "what are the colors of a rainbow" --temperature 0.5` 会发起新请求,因为我们在上一次请求中未提供 `--temperature``--top-probability` 同理)。
这只是我们使用 OpenAI GPT 模型可以实现的一些示例,相信你能在自己的特定用例中找到它们的用处。
### 运行时配置文件
你可以在运行时配置文件 `~/.config/shell_gpt/.sgptrc` 中设置一些参数:
```text
# API key, also it is possible to define OPENAI_API_KEY env.
OPENAI_API_KEY=your_api_key
# Base URL of the backend server. If "default" URL will be resolved based on --model.
API_BASE_URL=default
# Max amount of cached message per chat session.
CHAT_CACHE_LENGTH=100
# Chat cache folder.
CHAT_CACHE_PATH=/tmp/shell_gpt/chat_cache
# Request cache length (amount).
CACHE_LENGTH=100
# Request cache folder.
CACHE_PATH=/tmp/shell_gpt/cache
# Request timeout in seconds.
REQUEST_TIMEOUT=60
# Default OpenAI model to use.
DEFAULT_MODEL=gpt-5.4-mini
# Default color for shell and code completions.
DEFAULT_COLOR=magenta
# When in --shell mode, default to "Y" for no input.
DEFAULT_EXECUTE_SHELL_CMD=false
# Disable streaming of responses
DISABLE_STREAMING=false
# The pygment theme to view markdown (default/describe role).
CODE_THEME=default
# Path to a directory with functions.
OPENAI_FUNCTIONS_PATH=/Users/user/.config/shell_gpt/functions
# Print output of functions when LLM uses them.
SHOW_FUNCTIONS_OUTPUT=false
# Allows LLM to use functions.
OPENAI_USE_FUNCTIONS=true
# Enforce LiteLLM usage (for local LLMs).
USE_LITELLM=false
# Control how markdown live rendering handles overflow when output exceeds terminal height.
# Possible values: ellipsis, visible, crop
MARKDOWN_LIVE_VERTICAL_OVERFLOW=ellipsis
```
`DEFAULT_COLOR` 的可选值:black, red, green, yellow, blue, magenta, cyan, white, bright_black, bright_red, bright_green, bright_yellow, bright_blue, bright_magenta, bright_cyan, bright_white。
`CODE_THEME` 的可选值:https://pygments.org/styles/
`MARKDOWN_LIVE_VERTICAL_OVERFLOW` 的可选值:`ellipsis``visible``crop`
### 配置示例
**默认行为(省略号):**
```text
MARKDOWN_LIVE_VERTICAL_OVERFLOW=ellipsis
```
当 Markdown 输出超过终端高度时,仅显示 `...`。这是默认行为,可保持向后兼容。
**可见模式(推荐用于 REPL 会话):**
```text
MARKDOWN_LIVE_VERTICAL_OVERFLOW=visible
```
所有生成的 Markdown 内容都会实时可见。这对于长时间运行的 REPL 交互或智能体(agent)工作流尤其有用——你可以观察模型的推理过程、工具调用和中间输出。
```shell
sgpt --repl
```
`visible` 模式下,你可以持续观察生成的 Markdown 输出、工具执行详情和进度更新,而不必盯着 `...` 看上好几分钟。
### 完整参数列表
```text
╭─ Arguments ──────────────────────────────────────────────────────────────────────────────────────────────╮
│ prompt [PROMPT] The prompt to generate completions for. │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─ Options ────────────────────────────────────────────────────────────────────────────────────────────────╮
│ --model TEXT Large language model to use. [default: gpt-5.4-mini] │
│ --temperature FLOAT RANGE [0.0<=x<=2.0] Randomness of generated output. [default: 0.0] │
│ --top-p FLOAT RANGE [0.0<=x<=1.0] Limits highest probable tokens (words). [default: 1.0] │
│ --md --no-md Prettify markdown output. [default: md] │
│ --editor Open $EDITOR to provide a prompt. [default: no-editor] │
│ --cache Cache completion results. [default: cache] │
│ --version Show version. │
│ --help Show this message and exit. │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─ Assistance Options ─────────────────────────────────────────────────────────────────────────────────────╮
│ --shell -s Generate and execute shell commands. │
│ --interaction --no-interaction Interactive mode for --shell option. [default: interaction] │
│ --describe-shell -d Describe a shell command. │
│ --code -c Generate only code. │
│ --functions --no-functions Allow function calls. [default: functions] │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─ Chat Options ───────────────────────────────────────────────────────────────────────────────────────────╮
│ --chat TEXT Follow conversation with id, use "temp" for quick session. [default: None] │
│ --repl TEXT Start a REPL (Readevalprint loop) session. [default: None] │
│ --show-chat TEXT Show all messages from provided chat id. [default: None] │
│ --list-chats -lc List all existing chat ids. │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─ Role Options ───────────────────────────────────────────────────────────────────────────────────────────╮
│ --role TEXT System role for GPT model. [default: None] │
│ --create-role TEXT Create role. [default: None] │
│ --show-role TEXT Show role. [default: None] │
│ --list-roles -lr List roles. │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────╯
```
## Docker
使用 `OPENAI_API_KEY` 环境变量运行容器,并用 Docker 卷存储缓存。可根据个人偏好设置环境变量 `OS_NAME``SHELL_NAME`
```shell
docker run --rm \
--env OPENAI_API_KEY=api_key \
--env OS_NAME=$(uname -s) \
--env SHELL_NAME=$(echo $SHELL) \
--volume gpt-cache:/tmp/shell_gpt \
ghcr.io/ther1d/shell_gpt -s "update my system"
```
使用别名和 `OPENAI_API_KEY` 环境变量进行对话的示例:
```shell
alias sgpt="docker run --rm --volume gpt-cache:/tmp/shell_gpt --env OPENAI_API_KEY --env OS_NAME=$(uname -s) --env SHELL_NAME=$(echo $SHELL) ghcr.io/ther1d/shell_gpt"
export OPENAI_API_KEY="your OPENAI API key"
sgpt --chat rainbow "what are the colors of a rainbow"
sgpt --chat rainbow "inverse the list of your last answer"
sgpt --chat rainbow "translate your last answer in french"
```
你也可以使用提供的 `Dockerfile` 来构建自己的镜像:
```shell
docker build -t sgpt .
```
## 更多文档
* [Azure 集成](https://github.com/TheR1D/shell_gpt/wiki/Azure)
* [Ollama 集成](https://github.com/TheR1D/shell_gpt/wiki/Ollama)