diff --git a/README.md b/README.md index 072200b..be71b7e 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,10 @@ # Shell GPT -A command-line interface (CLI) productivity tool powered by OpenAI's Davinci model, that will help you accomplish your tasks faster and more efficiently. +A command-line productivity tool powered by OpenAI's ChatGPT (GPT-3.5). As developers, we can leverage ChatGPT capabilities to generate shell commands, code snippets, comments, and documentation, among other things. Forget about cheat sheets and notes, with this tool you can get accurate answers right in your terminal, and you'll probably find yourself reducing your daily Google searches, saving you valuable time and effort.
- +
-## Description -`text-davinci-003` is a powerful language model developed by OpenAI that can generate human-like text. It can be used by us developers, to generate code snippets, comments, documentation and more, helping us increase our productivity and efficiency while coding. - -Forget about cheat sheets and notes, with this tool you can get accurate answers right in your terminal, and you'll probably find yourself reducing your daily Google searches, saving you valuable time and effort. - ## Installation ```shell pip install shell-gpt --user @@ -19,17 +14,35 @@ On first start you would need to generate and provide your API key, get one [her ## Usage `sgpt` has a variety of use cases, including simple queries, shell queries, and code queries. ### Simple queries -We can use it pretty much as normal search engine, asking about anything, for example: +We can use it as normal search engine, asking about anything: ```shell sgpt "nginx default config file location" -# -> The default Nginx config location is /etc/nginx/nginx.conf +# -> The default configuration file for Nginx is located at /etc/nginx/nginx.conf. +``` +```shell sgpt "docker show all local images" # -> You can view all locally available Docker images by running: `docker images` +``` +```shell sgpt "mass of sun" # -> = 1.99 × 10^30 kg ``` -### Shell queries -Usually we are forgetting commands like `chmod 444` and we want quickly find the answer in google, but now we "google" and execute it right in the terminal using `--shell` flag `sgpt` will provide only shell commands: +### Conversion +Convert various units and measurements without having to search for the conversion formula or use a separate conversion website. You can convert units such as time, distance, weight, temperature, and more. +```shell +sgpt "1 hour and 30 minutes to seconds" +# -> 5,400 seconds +``` +```shell +sgpt "1 kilometer to mile" +# -> 1 kilometer is equal to 0.62137 miles. +``` +```shell +sgpt "$(date) to Unix timestamp" +# -> The Unix timestamp for Thu Mar 2 00:13:11 CET 2023 is 1677327191. +``` +### Shell commands +Have you ever found yourself forgetting common shell commands, such as `chmod`, and needing to look up the syntax online? With `--shell` option, you can quickly find and execute the commands you need right in the terminal. ```shell sgpt --shell "make all files in current directory read only" # -> chmod 444 * @@ -64,9 +77,9 @@ sgpt -se "using ffmpeg combine multiple videos into one without audio. Video fil # -> Execute shell command? [y/N]: y # ... ``` -Since GPT-3 models can also do summarization and analyzing of input text, we can ask `text-davinci-003` to generate commit message: +Since ChatGPT can also do summarization and analyzing of input text, we can ask it to generate commit message: ```shell -sgpt "Generate git commit message with details, my changes: $(git diff)" +sgpt "Generate git commit message, my changes: $(git diff)" # -> Commit message: Implement Model enum and get_edited_prompt() func, add temperature, top_p and editor args for OpenAI request. ``` Or ask it to find error in logs and provide more details: @@ -74,7 +87,7 @@ Or ask it to find error in logs and provide more details: sgpt "check these logs, find errors, and explain what the error is about: ${docker logs -n 20 container_name}" # ... ``` -### Code queries +### Generating code With `--code` parameters we can query only code as output, for example: ```shell sgpt --code "Solve classic fizz buzz problem using Python" @@ -102,26 +115,30 @@ python fizz_buzz.py # Fizz # ... ``` -This is, just some examples of what we can do using GPT-3 models, I'm sure you will find it useful for your specific use cases. +This is, just some examples of what we can do using ChatGPT model, I'm sure you will find it useful for your specific use cases. ### Full list of arguments ```shell -╭─ Arguments ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ -│ prompt [PROMPT] The prompt to generate completions for. │ -╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ -╭─ Options ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ -│ --model [davinci|curie|codex] GPT-3 model name. [default: davinci] │ -│ --max-tokens INTEGER Strict length of output (words). [default: (dynamic)] │ -│ --temperature FLOAT RANGE [0.0<=x<=1.0] Randomness of generated output. [default: (dynamic)] │ -│ --top-probability FLOAT RANGE [0.1<=x<=1.0] Limits highest probable tokens. [default: (dynamic)] │ -│ --shell -s Provide shell command as output. │ -│ --execute -e Will execute --shell command. │ -│ --code --no-code Provide code as output. [default: no-code] │ -│ --editor --no-editor Open $EDITOR to provide a prompt. [default: no-editor] │ -│ --animation --no-animation Typewriter animation. [default: animation] │ -│ --spinner --no-spinner Show loading spinner during API request. [default: spinner] │ -│ --help Show this message and exit. │ -╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ +╭─ Arguments ──────────────────────────────────────────────────────────────────────────────────────────────────╮ +│ prompt [PROMPT] The prompt to generate completions for. │ +╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ +╭─ Options ────────────────────────────────────────────────────────────────────────────────────────────────────╮ +│ --temperature FLOAT RANGE [0.0<=x<=1.0] Randomness of generated output. │ +│ [default: 1.0] │ +│ --top-probability FLOAT RANGE [0.1<=x<=1.0] Limits highest probable tokens (words). │ +│ [default: 1.0] │ +│ --shell -s Provide shell command as output. │ +│ --execute -e Will execute --shell command. │ +│ --code --no-code Provide code as output. │ +│ [default: no-code] │ +│ --editor --no-editor Open $EDITOR to provide a prompt. │ +│ [default: no-editor] │ +│ --animation --no-animation Typewriter animation. │ +│ [default: animation] │ +│ --spinner --no-spinner Show loading spinner during API request. │ +│ [default: spinner] │ +│ --help Show this message and exit. │ +╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ ``` ## Docker diff --git a/integrational_tests.py b/integrational_tests.py index d08cb87..f9a3921 100644 --- a/integrational_tests.py +++ b/integrational_tests.py @@ -33,33 +33,23 @@ class TestCliApp(TestCase): if isinstance(value, bool): continue arguments.append(value) - # arguments.extend([kv for kv in kwargs.items() for kv in kv]) return arguments def test_simple_queries(self): - dict_arguments = { - "prompt": "What is the capital of the Czech Republic?", - "--max-tokens": 32, - "--model": "curie", - } + dict_arguments = {"prompt": "What is the capital of the Czech Republic?"} result = runner.invoke(app, self.get_arguments(**dict_arguments)) assert result.exit_code == 0 assert "Prague" in result.stdout def test_shell_queries(self): - dict_arguments = { - "prompt": "make a commit using git", - "--max-tokens": 32, - "--model": "davinci", - "--shell": True, - } + dict_arguments = {"prompt": "make a commit using git", "--shell": True} result = runner.invoke(app, self.get_arguments(**dict_arguments)) assert result.exit_code == 0 assert "git commit" in result.stdout def test_code_queries(self): """ - This test will request from GPT-3 a python code to make CLI app, + This test will request from ChatGPT a python code to make CLI app, which will be written to a temp file, and then it will be executed in shell with two positional int arguments. As the output we are expecting the result of multiplying them. @@ -70,8 +60,6 @@ class TestCliApp(TestCase): "accepts two integer positional command line arguments " "and prints the result of multiplying them." ), - "--max-tokens": 128, - "--model": "davinci", "--code": True, } result = runner.invoke(app, self.get_arguments(**dict_arguments)) diff --git a/setup.py b/setup.py index 1b92c75..eccb5f7 100644 --- a/setup.py +++ b/setup.py @@ -3,7 +3,7 @@ from setuptools import setup, find_packages # pylint: disable=consider-using-with setup( name="shell_gpt", - version="0.5.1", + version="0.6.0", packages=find_packages(), py_modules=[ "sgpt", @@ -18,7 +18,10 @@ setup( }, author="Farkhod Sadykov", author_email="farkhod@sadykov.dev", - description="CLI App allows to query OpenAI GPT-3 models using API.", + description=( + "A command-line productivity tool powered by ChatGPT, " + "will help you accomplish your tasks faster and more efficiently." + ), long_description=open("README.md").read(), long_description_content_type="text/markdown", url="https://github.com/ther1d/shell_gpt", diff --git a/sgpt.py b/sgpt.py index a7768d3..326f9a9 100644 --- a/sgpt.py +++ b/sgpt.py @@ -1,7 +1,7 @@ """ -shell-gpt: An interface to OpenAI's GPT-3 API +shell-gpt: An interface to OpenAI's ChatGPT (GPT-3.5) API -This module provides a simple interface for OpenAI's GPT-3 API using Typer +This module provides a simple interface for OpenAI's ChatGPT API using Typer as the command line interface. It supports different modes of output including shell commands and code, and allows users to specify the desired OpenAI model and length and other options of the output. Additionally, it supports executing @@ -13,11 +13,9 @@ API Key is stored locally for easy use in future runs. import os import platform -from enum import Enum from time import sleep from pathlib import Path from getpass import getpass -from types import DynamicClassAttribute from tempfile import NamedTemporaryFile import typer @@ -28,28 +26,11 @@ from click import MissingParameter, BadParameter from rich.progress import Progress, SpinnerColumn, TextColumn -API_URL = "https://api.openai.com/v1/completions" +API_URL = "https://api.openai.com/v1/chat/completions" DATA_FOLDER = os.path.expanduser("~/.config") KEY_FILE = Path(DATA_FOLDER) / "shell-gpt" / "api_key.txt" -# pylint: disable=invalid-name -class Model(str, Enum): - davinci = "text-davinci-003" - curie = "text-curie-001" - codex = "code-davinci-002" - - def __str__(self): - return self.name - - @DynamicClassAttribute - def value(self): - return self.name - - -# pylint: enable=invalid-name - - def get_api_key(): if not KEY_FILE.exists(): api_key = getpass(prompt="Please enter your API secret key") @@ -64,7 +45,7 @@ def loading_spinner(func): def wrapper(*args, **kwargs): if not kwargs.pop("spinner"): return func(*args, **kwargs) - text = TextColumn("[green]Requesting OpenAI...") + text = TextColumn("[green]Consulting with robots...") with Progress(SpinnerColumn(), text, transient=True) as progress: progress.add_task("request") return func(*args, **kwargs) @@ -89,18 +70,17 @@ def get_edited_prompt(): @loading_spinner -def openai_request(prompt, model, max_tokens, api_key, temperature, top_p): +def openai_request(prompt, api_key, temperature, top_p): headers = {"Content-Type": "application/json", "Authorization": f"Bearer {api_key}"} data = { - "prompt": prompt, - "model": model, - "max_tokens": max_tokens, + "messages": [{"role": "user", "content": prompt}], + "model": "gpt-3.5-turbo", "temperature": temperature, "top_p": top_p, } - response = requests.post(API_URL, headers=headers, json=data, timeout=180) + response = requests.post(API_URL, headers=headers, json=data, timeout=30) response.raise_for_status() - return response.json()["choices"][0]["text"] + return response.json()["choices"][0]["message"]["content"] def typer_writer(text, code, shell, animate): @@ -119,10 +99,8 @@ def typer_writer(text, code, shell, animate): # Using lambda to pass a function to default value, which make it appear as "dynamic" in help. def main( prompt: str = typer.Argument(None, show_default=False, help="The prompt to generate completions for."), - model: Model = typer.Option("davinci", help="GPT-3 model name.", show_choices=True), - max_tokens: int = typer.Option(lambda: 2048, help="Strict length of output (words)."), - temperature: float = typer.Option(lambda: 1.0, min=0.0, max=1.0, help="Randomness of generated output."), - top_probability: float = typer.Option(lambda: 1.0, min=0.1, max=1.0, help="Limits highest probable tokens."), + temperature: float = typer.Option(1.0, min=0.0, max=1.0, help="Randomness of generated output."), + top_probability: float = typer.Option(1.0, min=0.1, max=1.0, help="Limits highest probable tokens (words)."), shell: bool = typer.Option(False, "--shell", "-s", help="Provide shell command as output."), execute: bool = typer.Option(False, "--execute", "-e", help="Will execute --shell command."), code: bool = typer.Option(False, help="Provide code as output."), @@ -134,32 +112,28 @@ def main( if not prompt and not editor: raise MissingParameter(param_hint="PROMPT", param_type="string") if shell: - # If default values where not changed, make it more accurate. - if temperature == 1.0 == top_probability: - temperature, top_probability = 0.2, 1.0 + # If probability and temperature were not changed (default), make response more accurate. + if top_probability == 1 == temperature: + temperature = 0.4 current_shell = "PowerShell" if platform.system() == "Windows" else "Bash" - prompt = f""" - Context: Provide only {current_shell} command as output. - Prompt: {prompt} - Command: - """ + prompt = f"""Provide only {current_shell} command as output, without any additional text or prompt. + {prompt}""" elif code: - # If default values where not changed, make output more creative (diverse). - if temperature == 1.0 == top_probability: - temperature, top_probability = 0.8, 0.2 - prompt = f""" - Context: Provide only code as output. - Prompt: {prompt} - Code: - """ - # Curie has hard cap 2048 + prompt. - if model == "text-curie-001" and max_tokens == 2048: - max_tokens = 1024 + prompt = f"""Provide code and only code as output without any additional text, prompt or note. + {prompt}""" if editor: prompt = get_edited_prompt() - response_text = openai_request(prompt, model, max_tokens, api_key, temperature, top_probability, spinner=spinner) + response_text = openai_request(prompt, api_key, temperature, top_probability, spinner=spinner) # For some reason OpenAI returns several leading/trailing white spaces. response_text = response_text.strip() + if code: + # Responses from GPT-3.5 wrapped into Markdown code block. + lines = response_text.split("\n") + if lines[0].startswith("```"): + del lines[0] + if lines[-1].startswith("```"): + del lines[-1] + response_text = "\n".join(lines) typer_writer(response_text, code, shell, animation) if shell and execute and typer.confirm("Execute shell command?"): os.system(response_text) diff --git a/unittests.py b/unittests.py index 9ed2a49..b38172b 100644 --- a/unittests.py +++ b/unittests.py @@ -7,8 +7,6 @@ import sgpt class TestMain(unittest.TestCase): def setUp(self): self.prompt = "What is the capital of France?" - self.model = "text-davinci-003" - self.max_tokens = 2048 self.shell = False self.execute = False self.code = False @@ -21,15 +19,13 @@ class TestMain(unittest.TestCase): @requests_mock.Mocker() def test_openai_request(self, mock): - mock.post(sgpt.API_URL, json={"choices": [{"text": self.response_text}]}, status_code=200) - result = sgpt.openai_request( - self.prompt, self.model, self.max_tokens, self.api_key, self.temperature, self.top_p, spinner=self.spinner - ) + mocked_json = {"choices": [{"message": {"content": self.response_text}}]} + mock.post(sgpt.API_URL, json=mocked_json, status_code=200) + result = sgpt.openai_request(self.prompt, self.api_key, self.temperature, self.top_p, spinner=self.spinner) self.assertEqual(result, self.response_text) expected_json = { - "prompt": self.prompt, - "model": self.model, - "max_tokens": self.max_tokens, + "messages": [{"role": "user", "content": self.prompt}], + "model": "gpt-3.5-turbo", "temperature": self.temperature, "top_p": self.top_p, } @@ -45,8 +41,6 @@ class TestMain(unittest.TestCase): with self.assertRaises(requests.exceptions.HTTPError): sgpt.openai_request( self.prompt, - self.model, - self.max_tokens, self.api_key, self.temperature, self.top_p,