AI 대형 언어 모델 (LLM)으로 구동되는 명령 줄 생산성 도구. 이 명령 줄 도구는 간소화 된 쉘 명령, 코드 스 니펫, 문서화를 제공하여 Google 검색과 같은 외부 리소스의 필요성을 제거합니다. Linux, MacO, Windows를 지원하며 PowerShell, CMD, Bash, ZSH 등과 같은 모든 주요 쉘과 호환됩니다.
pip install shell-gpt
기본적으로 Shellgpt는 OpenAI의 API 및 GPT-4 모델을 사용합니다. API 키가 필요하고 여기에서 하나를 생성 할 수 있습니다. 당신은 당신의 키에 대한 프롬프트가 ~/.config/shell_gpt/.sgptrc
에 저장됩니다. OpenAI API는 무료가 아닙니다. 자세한 내용은 OpenAI 가격을 참조하십시오.
팁
또는 무료로 제공되는 로컬로 호스팅되는 오픈 소스 모델을 사용할 수 있습니다. 로컬 모델을 사용하려면 Ollama와 같은 LLM 백엔드 서버를 실행해야합니다. Ollama와 함께 Shellgpt를 설정하려면이 포괄적 인 가이드를 따르십시오.
shellgpt가 로컬 모델에 최적화되지 않았으며 예상대로 작동하지 않을 수 있습니다.
Shellgpt는 정보를 신속하게 분석하고 검색하도록 설계되었습니다. 기술 구성에서 일반 지식에 이르기까지 간단한 요청에 유용합니다.
sgpt " What is the fibonacci sequence "
# -> The Fibonacci sequence is a series of numbers where each number ...
Shellgpt는 stdin 및 command line 인수 모두에서 프롬프트를 수락합니다. 터미널을 통한 배관 입력을 선호하든 인수로 직접 지정하든 sgpt
귀하를 덮었습니다. 예를 들어, diff를 기반으로 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 Command를 제공합니다. 예를 들어, sgpt
에 시스템을 업데이트하도록 요청하면 OS에 따라 명령을 반환합니다. 다음은 MacOS를 사용하는 예입니다.
sgpt -s " update my system "
# -> sudo softwareupdate -i -a
# -> [E]xecute, [D]escribe, [A]bort: e
우분투에서 사용될 때 동일한 프롬프트는 다른 제안을 생성합니다.
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
에 입력을 전달하고 쉘 명령을 생성 할 수 있습니다.
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
파이프를 사용하여 생성 된 쉘 명령을 전달하려면 --no-interaction
옵션을 사용할 수 있습니다. 이것은 대화식 모드를 비활성화하고 생성 된 명령을 stdout에 인쇄합니다. 이 예에서는 pbcopy
사용하여 생성 된 명령을 클립 보드에 복사합니다.
sgpt -s " find all json files in current folder " --no-interaction | pbcopy
이것은 매우 편리한 기능으로 , 신속하고 인수와 함께 sgpt
입력 할 필요없이 터미널에서 직접 sgpt
쉘 완성을 사용할 수 있습니다. Shell Integration을 사용하면 Bash 및 Zsh Shells가 지원하는 터미널에 Hotkeys와 함께 Shellgpt를 사용할 수 있습니다. 이 기능은 sgpt
완료를 터미널 버퍼 (입력 라인)로 직접 배치하여 제안 된 명령을 즉시 편집 할 수 있습니다.
쉘 통합을 설치하려면 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 )
유효한 파이썬 코드이므로 출력을 파일로 리디렉션 할 수 있습니다.
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 완성과 대화 대화를 만듭니다. 대화는 REPL 루프 (REPL 모드)에서 일대일 (채팅 모드) 또는 대화식으로 개발할 수 있습니다. 두 가지 방법은 채팅 세션이라고 불리는 동일한 기본 객체에 의존합니다. 세션은 구성 가능한 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 (Read – Eval -Print Loop) 모드가있어 GPT 모델과 대화식으로 채팅 할 수 있습니다. Repl 모드에서 채팅 세션을 시작하려면 --repl
옵션을 사용하고 고유 한 세션 이름을 사용하십시오. "Temp"를 세션 이름으로 사용하여 임시 답변 세션을 시작할 수도 있습니다. --chat
및 --repl
은 동일한 기본 객체를 사용하므로 --chat
사용하여 채팅 세션을 시작한 다음 --repl
선택하여 대화 모드에서 대화를 계속할 수 있습니다.
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
옵션으로 작동하여 대화식 쉘 명령 및 코드 생성에 매우 편리합니다.
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)
멀티 라인 프롬프트를 제공하려면 트리플 Quotes """
:
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 모드를 입력 할 수도 있습니다.
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 } "
클래스 내부의 문서 주석은 title
속성 및 매개 변수 설명과 함께 함수에 대한 설명으로 OpenAI API로 전달됩니다. LLM이 기능을 사용하기로 결정하면 execute
함수가 호출됩니다. 이 경우 LLM이 시스템에서 쉘 명령을 실행할 수 있습니다. 명령의 출력을 반환하기 때문에 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 파일이 생성됩니다. 이 디렉토리 내에서 Shell , Code 및 Default 와 같은 기본 sgpt
역할을 편집 할 수도 있습니다. --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 Cignitive)이 포함 된 경우 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_Cyan, 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"]