shell_gpt

其他资源 2025-08-22

贝壳

由AI大语言模型(LLM)提供动力的命令行生产力工具。此命令行工具提供了简化的外壳命令,代码段,文档,消除了对外部资源的需求(例如Google搜索)。支持Linux,MacOS,Windows,并与PowerShell,CMD,Bash,Zsh等所有主要外壳兼容。

shellgpt.mp4

安装

pip install shell-gpt

默认情况下,ShellGPT使用OpenAI的API和GPT-4模型。您需要一个API密钥,可以在此处生成一个。将提示您的密钥,然后将其存储在〜/.config/ shell_gpt /.sgptrc中。 OpenAI API不是免费的,请参阅OpenAI定价以获取更多信息。

提示

另外,您可以免费使用可免费使用的本地托管的开源模型。要使用本地型号,您将需要运行自己的LLM后端服务器(例如Ollama)。要与Ollama建立ShellGPT,请遵循此综合指南。

❗️指出,ShellGPT并未针对本地模型进行优化,并且可能无法按预期工作。

用法

ShellGPT旨在快速分析和检索信息。这对于从技术配置到通用知识的直接请求很有用。

sgpt " What is the fibonacci sequence "
# -> The Fibonacci sequence is a series of numbers where each number ...

ShellGPT接受stdin和命令行参数的提示。无论您喜欢通过终端输入管道输入还是直接按照参数指定,SGPT都会覆盖您。例如,您可以根据差异轻松地生成git提交消息:

git diff | sgpt " Generate git commit message, for my changes "
# -> Added main feature details into README.md

您可以通过使用STDIN传递各种来源的日志以及提示。例如,我们可以使用它来快速分析日志,识别错误并获取有关解决方案的建议:

docker logs -n 20 my_app | sgpt " check logs, find errors, provide possible solutions " 
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.

您也可以使用各种重定向操作员传递输入:

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或快捷方式-S选项,您可以在终端中快速生成并执行所需的命令。

sgpt --shell " find all json files in current folder "
# -> find . -type f -name "*.json"
# -> [E]xecute, [D]escribe, [A]bort: e

Shell GPT知道您正在使用的OS和$ Shell,它将为您拥有的特定系统提供Shell命令。例如,如果您要求SGPT更新系统,它将根据您的操作系统返回命令。这是使用MacOS的示例:

sgpt -s " update my system "
# -> sudo softwareupdate -i -a
# -> [E]xecute, [D]escribe, [A]bort: e

在Ubuntu上使用相同的提示将产生不同的建议:

sgpt -s " update my system "
# -> sudo apt update && sudo apt upgrade -y
# -> [E]xecute, [D]escribe, [A]bort: e

让我们与Docker一起尝试:

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命令:

curl -X POST -H "Content-Type: application/json" -d '{"a": 1, "b": 2}' http://l**oc*alhost # -> [E]xecute, [D]escribe, [A]bort: e">
sgpt -s " POST localhost with " < data.json
# -> curl -X POST -H "Content-Type: application/json" -d '{"a": 1, "b": 2}' http://l**oc*alhost
# -> [E]xecute, [D]escribe, [A]bort: e

在我们的提示中应用其他外壳魔术,在此示例中,将文件名传递给ffmpeg:

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 Itteraction选项。这将禁用交互式模式,并将打印生成的命令对Stdout。在此示例中,我们使用PBCopy将生成的命令复制到剪贴板:

sgpt -s " find all json files in current folder " --no-interaction | pbcopy

壳集成

这是一个非常方便的功能,它允许您直接在终端中使用SGPT Shell完成,而无需使用及时的sgpt键入SGPT。 Shell Integration可以在您的终端中使用Hotkeys使用ShellGPT,并由Bash和Zsh壳支持。此功能将SGPT完整直接放入终端缓冲区(输入线),允许立即编辑建议的命令。

要安装Shell Integration,请运行SGPT-Antall-Integration,然后重新启动您的终端以应用更改。这将为您的.bashrc或.zshrc文件添加几行。之后,您可以使用CTRL+L(默认情况下)调用ShellGPT。当您按CTRL+L时,它将用建议的命令替换当前输入线(缓冲区)。然后,您可以对其进行编辑,然后按Enter执行。

生成代码

通过使用-CODE或-C参数,您可以特别请求纯代码输出,例如:

sgpt --code " solve fizz buzz problem using 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代码,因此我们可以将输出重定向到文件:

sgpt --code " solve classic fizz buzz problem using Python " > fizz_buzz.py
python fizz_buzz.py
# 1
# 2
# Fizz
# 4
# Buzz
# ...

我们还可以使用管道传递输入:

cat fizz_buzz.py | sgpt --code " Generate comments for each line of my code " 
 # 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完成中创建对话对话。对话可以在一个depl循环(depp模式)中进行一对一或互动开发。这两种方式都依靠同一基础对象,称为聊天会话。该会话位于可配置的CHAT_CACHE_PATH上。

要启动对话,请使用-Chat选项,然后使用唯一的会话名和提示。

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.

您可以通过提供其他详细信息来使用聊天会议来迭代地改善GPT建议。可以使用 - 编码或-shell选项来启动-Chat:

sgpt --chat conversation_2 --code " make a request to localhost using python " 
 import requests

response = requests . get ( 'http://l**oc*alhost' )
print ( response . text )

让我们要求LLM添加缓存,以应对我们的要求:

sgpt --chat conversation_2 --code " add caching " 
 import requests
from cachecontrol import CacheControl

sess = requests . session ()
cached_sess = CacheControl ( sess )

response = cached_sess . get ( 'http://l**oc*alhost' )
print ( response . text )

外壳命令同样适用:

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">
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 -chat或-lc选项:

shell_gpt/chat_cache/conversation_1 # .../ shell_gpt /chat_cache/conversation_2">
sgpt --list-chats
# .../ shell_gpt /chat_cache/conversation_1  
# .../ shell_gpt /chat_cache/conversation_2

要显示与特定对话有关的所有消息,请使用-show-chat选项,然后使用会话名称:

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(读取 - eval -print循环)模式,它使您可以与GPT模型进行交互性聊天。要以模式启动聊天会话,请使用-repl选项,然后使用唯一的会话名称。您还可以将“临时”用作会话名来开始临时repl会话。请注意,-Chat和-repl使用相同的基础对象,因此您可以使用-Chat开始聊天会话,然后使用-Repl将其拾取以在REPP模式下继续对话。

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 ...

复制模式可以与 - shell和 - 代码选项一起使用,这对于交互式壳命令和代码生成非常方便:

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)

提供多行提示使用三重引号“”:

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传递,甚至两者兼而有之输入模式:

sgpt --repl temp < my_app.py
>> What is this code about? The snippet of code you've provided is written in Python. It prompts the user... >>> Follow up questions...">
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...

函数调用

功能调用是OpenAI提供的强大功能。它允许LLM在系统中执行功能,该功能可用于完成各种任务。安装默认函数运行:

sgpt --install-functions

ShellGPT具有定义功能并使用功能的方便方法。为了创建您的自定义函数,请导航到〜/.config/ shell_gpt /functions,并使用功能名称创建一个新的.py文件。在此文件中,您可以使用以下语法来定义您的函数:

 # execute_shell_command.py
import subprocess
from pydantic import Field
from instructor import OpenAISchema


class Function ( OpenAISchema ):
    """
    Executes a shell command and returns the output (result).
    """
    shell_command : str = Field (..., example = "ls -la" , descriptions = "Shell command to execute." )

    class Config :
        title = "execute_shell_command"

    @ classmethod
    def execute ( cls , shell_command : str ) -> str :
        result = subprocess . run ( shell_command . split (), capture_output = True , text = True )
        return f"Exit code: { result . returncode } , Output: n { result . stdout } "

同类中的DocString注释将传递给OpenAI API,作为该函数的描述,以及标题属性和参数描述。如果LLM决定使用您的函数,则将调用执行函数。在这种情况下,我们允许LLM执行系统中的任何Shell命令。由于我们正在返回命令的输出,LLM将能够分析并确定它是否适合提示。这是一个示例LLM可以执行该函数的示例:

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文件:

@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.">
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.

也可以在提示中链接多个函数调用:

sgpt " Play music and open hacker news "
# -> @FunctionCall play_music()
# -> @FunctionCall open_url(url="https://news.yco*mbina*t*or.com")
# -> Music is now playing, and Hacker News has been opened in your browser. Enjoy!

这只是如何使用函数调用的一个简单示例。它确实是一个强大的功能,可用于完成各种复杂的任务。我们在GitHub讨论中有专门的类别,用于共享和讨论功能。 LLM可能会执行破坏性命令,因此请以您自己的风险使用它

角色

ShellGPT允许您创建自定义角色,可以将其用于生成代码,外壳命令或满足您的特定需求。要创建一个新角色,请使用-create-lole选项,然后使用角色名称。将提示您为角色提供描述以及其他细节。这将在〜/.config/ shell_gpt /角色中创建一个带有角色名称的JSON文件。在此目录中,您还可以编辑默认的SGPT角色,例如ShellCodeDefault 。使用-List-Ololes选项列出所有可用的角色,以及-Show-lole选项,以显示特定角色的详细信息。这是自定义角色的一个示例:

sgpt --create-role json_generator
# Enter role description: Provide only valid json as response.
sgpt --role json_generator " random: user, password, email, address " 
{
  "user" : " JohnDoe " ,
  "password" : " p@ssw0rd " ,
  "email" : " johndoe@example.com " ,
  "address" : {
    "street" : " 123 Main St " ,
    "city" : " Anytown " ,
    "state" : " CA " ,
    "zip" : " 12345 "
  }
}

如果该角色的描述包含单词“ apply markdown”(case敏感),则除非用-NO-MD明确关闭,否则将使用Markdown格式显示聊天。

请求缓存

使用-CACHE(默认)和-NO-CACHE选项控制缓存。此缓存适用于OpenAI API的所有SGPT请求:

sgpt " what are the colors of a rainbow "
# -> The colors of a rainbow are red, orange, yellow, green, blue, indigo, and violet.

下次,相同的查询将立即从本地缓存获得结果。请注意,SGPT“彩虹的颜色是什么” - 温度0.5将提出新的请求,因为我们不提供以前的请求的 - 温度(同样适用于 - top概率)。

这只是使用OpenAI GPT型号可以做什么的一些示例,我敢肯定,您会发现它对您的特定用例有用。

运行时配置文件

您可以在运行时配置文件中设置某些参数〜/.config/ shell_gpt /.sgptrc:

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-4o # 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">
# 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-4o
# 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

Default_Color的可能选项:黑色,红色,绿色,黄色,蓝色,洋红色,青色,白色,白色,bright_black,bright_red,bright_green,bright_yellow,bright_blue,bright_magenta,bright_magenta,bright_cyan,bright_white,bright_white。 code_theme的可能选项:https://pygments.org/styles/

参数的完整列表

╭─ Arguments ──────────────────────────────────────────────────────────────────────────────────────────────╮
│   prompt      [PROMPT]  The prompt to generate completions for.                                          │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─ Options ────────────────────────────────────────────────────────────────────────────────────────────────╮
│ --model            TEXT                       Large language model to use. [default: gpt-4o]             │
│ --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 (Read–eval–print 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_gpt ghcr.io/ther1d/ shell_gpt -s "update my system"">
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_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"">
 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来构建自己的图像:

docker build -t sgpt .

Docker + Ollama

如果要将请求发送到Ollama实例并在Docker容器中运行ShellGpt,则需要调整Dockerfile并自己构建容器:需要LITELLM软件包,并且需要正确设置ENV变量。

示例Dockerfile:

shell_gpt VOLUME /tmp/ shell_gpt ENTRYPOINT ["sgpt"]">
FROM python:3-slim

ENV DEFAULT_MODEL=ollama/mistral:7b-instruct-v0.2-q4_K_M
ENV API_BASE_URL=http://10.10.1***0.10:11434
ENV USE_LITELLM=true
ENV OPENAI_API_KEY=bad_key
ENV SHELL_INTERACTION=false
ENV PRETTIFY_MARKDOWN=false
ENV OS_NAME="Arch Linux"
ENV SHELL_NAME=auto

WORKDIR /app
COPY . /app

RUN apt-get update && apt-get install -y gcc
RUN pip install --no-cache /app[litellm] && mkdir -p /tmp/ shell_gpt

VOLUME /tmp/ shell_gpt

ENTRYPOINT ["sgpt"]

附加文档

  • Azure集成
  • Ollama整合
下载源码

通过命令行克隆项目:

git clone https://github.com/TheR1D/shell_gpt.git