由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"]