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の価格を参照してください。
ヒント
または、無料で利用できるローカルホストのオープンソースモデルを使用できます。ローカルモデルを使用するには、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とコマンドラインの両方の引数からプロンプトを受け入れます。ターミナルからの配管入力を好むか、それを引数として直接指定するかどうかにかかわらず、 sgptあなたをカバーしました。たとえば、diffに基づいてgitコミットメッセージを簡単に生成できます。
git diff | sgpt " Generate git commit message, for my changes "
# -> Added main feature details into README.mdStdinを使用してプロンプトとともに渡すことにより、さまざまなソースからのログを分析できます。たとえば、それを使用して、ログをすばやく分析し、エラーを特定し、可能なソリューションの提案を得ることができます。
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またはshortcut -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を認識しており、あなたが持っている特定のシステムにシェルコマンドを提供します。たとえば、 sgptシステムを更新するように依頼すると、OSに基づいてコマンドを返します。これが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: eDockerで試してみましょう:
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 Pipeを使用して生成されたシェルコマンドを渡す場合は、 --no-interactionオプションを使用できます。これにより、インタラクティブモードが無効になり、生成されたコマンドをstdoutに印刷します。この例では、 pbcopyを使用して、生成されたコマンドをクリップボードにコピーしています。
sgpt -s " find all json files in current folder " --no-interaction | pbcopyこれは非常に便利な機能であり、SGPTと引数を使用してsgptを入力する必要なく、端末で直接sgptシェル完成を使用できます。シェル統合により、ターミナルにホットキーを使用してshellgptを使用して、bashシェルとzshシェルの両方でサポートされます。この機能により、 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 )有効な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完了を使用して会話の対話を作成します。ダイアログは、REPLループ(REPLモード)で1つずつ(チャットモード)またはインタラクティブに開発できます。両方の方法で、チャットセッションと呼ばれる同じ基礎となるオブジェクトに依存しています。セッションは、構成可能な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」をセッション名として使用して、一時的なREPLセッションを開始することもできます。 --chatと--replは同じ基礎となるオブジェクトを使用しているため、 --chatを使用してチャットセッションを開始してから、 --replで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)
マルチラインプロンプトを提供するには、トリプルクォートを使用する""" :
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 } "クラス内のDocStringコメントは、 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ファイルが作成されます。このディレクトリ内では、シェル、コード、デフォルトなどのデフォルトの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 "
}
}役割の説明に「Markdownを適用する」という単語(ケースに敏感)が含まれている場合、Markdownフォーマットを使用してチャットが表示されます。
--cache (default)および--no-cacheオプションを使用してキャッシュを制御します。このキャッシングは、すべてのsgptリクエストにOpenAI APIに適用されます。
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_yello、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"]