由AI大语言模型(LLM)提供动力的命令行生产力工具。此命令行工具提供了简化的外壳命令,代码段,文档,消除了对外部资源的需求(例如Google搜索)。支持Linux,MacOS,Windows,并与PowerShell,CMD,Bash,Zsh等所有主要外壳兼容。
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...您是否曾经发现自己忘记了诸如find类的常见外壳命令,并且需要在线查找语法?使用--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命令:
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在我们的提示中应用其他外壳魔术,在此示例中,将文件名传递给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-interaction选项。这将禁用交互式模式,并将打印生成的命令对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 --install-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建议。可以使用--code或--shell选项来启动--chat :
sgpt --chat conversation_2 --code " make a request to localhost using python " import requests
response = requests . get ( 'http://localhost' )
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://localhost' )
print ( response . text )外壳命令同样适用:
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选项:
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和--code选项一起使用,这对于交互式壳命令和代码生成非常方便:
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 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,作为该功能的描述,以及title属性和参数描述。如果LLM决定使用您的函数,则将调用execute函数。在这种情况下,我们允许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文件:
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.ycombinator.com")
# -> Music is now playing, and Hacker News has been opened in your browser. Enjoy!这只是如何使用函数调用的一个简单示例。它确实是一个强大的功能,可用于完成各种复杂的任务。我们在GitHub讨论中有专门的类别,用于共享和讨论功能。 LLM可能会执行破坏性命令,因此请以您自己的风险使用它
ShellGPT允许您创建自定义角色,可以将其用于生成代码,外壳命令或满足您的特定需求。要创建一个新角色,请使用--create-role选项,然后使用角色名称。将提示您为角色提供描述以及其他细节。这将在~/.config/shell_gpt/roles中创建一个带有角色名称的JSON文件。在此目录中,您还可以编辑默认的sgpt角色,例如Shell , Code和Default 。使用--list-roles选项列出所有可用的角色,以及--show-role选项,以显示特定角色的详细信息。这是自定义角色的一个示例:
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" : " [email protected] " ,
"address" : {
"street" : " 123 Main St " ,
"city" : " Anytown " ,
"state" : " CA " ,
"zip" : " 12345 "
}
}如果该角色的描述包含“ apply markdown”(case敏感)的单词,则将使用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 "what are the colors of a rainbow" --temperature 0.5将提出新的请求,因为我们不提供以前的请求的--temperature (同样适用于--top-probability )。
这只是使用OpenAI GPT型号可以做什么的一些示例,我敢肯定,您会发现它对您的特定用例有用。
您可以在运行时配置文件中设置某些参数~/.config/shell_gpt/.sgptrc :
# 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. │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────╯
使用OPENAI_API_KEY环境变量运行容器,以及用于存储缓存的Docker卷。考虑根据您的喜好设置环境变量OS_NAME和SHELL_NAME 。
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环境变量:
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 .如果要将请求发送到Ollama实例并在Docker容器中运行ShellGpt,则需要调整Dockerfile并自己构建容器:需要LITELLM软件包,并且需要正确设置ENV变量。
示例Dockerfile:
FROM python:3-slim
ENV DEFAULT_MODEL=ollama/mistral:7b-instruct-v0.2-q4_K_M
ENV API_BASE_URL=http://10.10.10.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"]