Real time streaming and prompt engineering

* Better shell recognition for windows

* Added real time streaming and fix colors

* Prompt engineering, minor improvements and fixes

* Removed typerwrited function from utils

---------
Co-authored-by: Farkhod Sadykov <farkhod.sadykov@gmail.com>
This commit is contained in:
Parsa
2023-03-28 19:32:11 +03:30
committed by GitHub
parent caa4fbfb8e
commit fc59c234ce
8 changed files with 156 additions and 191 deletions
+7 -15
View File
@@ -40,39 +40,34 @@ sgpt "1 kilometer to miles"
# -> 1 kilometer is equal to 0.62137 miles.
```
### 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.
Have you ever found yourself forgetting common shell commands, such as `chmod`, and needing to look up the syntax online? With `--shell` or shortcut `-s` 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 *
```
Since we are receiving valid shell command, we can execute it using `eval $(sgpt --shell "make all files in current directory read only")` but this is not very convenient, instead we can use `--execute` (or shortcut `-se` for `--shell` `--execute`) parameter:
```shell
sgpt --shell --execute "make all files in current directory read only"
# -> chmod 444 *
# -> Execute shell command? [y/N]: y
# ...
```
Shell GPT is aware of OS and `$SHELL` you are using, it will provide shell command for specific system you have. For instance, if you ask `sgpt` to update your system, it will return a command based on your OS. Here's an example using macOS:
```shell
sgpt -se "update my system"
sgpt -s "update my system"
# -> sudo softwareupdate -i -a
```
The same prompt, when used on Ubuntu, will generate a different suggestion:
```shell
sgpt -se "update my system"
sgpt -s "update my system"
# -> sudo apt update && sudo apt upgrade -y
```
Let's try some docker containers:
```shell
sgpt -se "start nginx using docker, forward 443 and 80 port, mount current folder with index.html"
sgpt -s "start nginx using docker, forward 443 and 80 port, mount current folder with index.html"
# -> docker run -d -p 443:443 -p 80:80 -v $(pwd):/usr/share/nginx/html nginx
# -> Execute shell command? [y/N]: y
# ...
```
Also, we can provide some parameters name in our prompt, for example, passing output file name to ffmpeg:
```shell
sgpt -se "slow down video twice using ffmpeg, input video name \"input.mp4\" output video name \"output.mp4\""
sgpt -s "slow down video twice using ffmpeg, input video name \"input.mp4\" output video name \"output.mp4\""
# -> ffmpeg -i input.mp4 -filter:v "setpts=2.0*PTS" output.mp4
# -> Execute shell command? [y/N]: y
# ...
@@ -81,7 +76,7 @@ We can apply additional shell magic in our prompt, in this example passing file
```shell
ls
# -> 1.mp4 2.mp4 3.mp4
sgpt -se "using ffmpeg combine multiple videos into one without audio. Video file names: $(ls -m)"
sgpt -s "using ffmpeg combine multiple videos into one without audio. Video file names: $(ls -m)"
# -> 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
# -> Execute shell command? [y/N]: y
# ...
@@ -225,13 +220,10 @@ REQUEST_TIMEOUT=60
│ --chat TEXT Follow conversation with id (chat mode). [default: None] │
│ --show-chat TEXT Show all messages from provided chat id. [default: None] │
│ --list-chat List all existing chat ids. [default: no-list-chat] │
│ --shell Provide shell command as output. │
│ --execute Will execute --shell command. │
│ --shell Generate and execute shell command. │
│ --code Provide code as output. [default: no-code] │
│ --editor Open $EDITOR to provide a prompt. [default: no-editor] │
│ --cache Cache completion results. [default: cache] │
│ --animation Typewriter animation. [default: animation] │
│ --spinner Show loading spinner during API request. [default: spinner] │
│ --help Show this message and exit. │
╰───────────────────────────────────────────────────────────────────────────────────────────────────────────╯
```
+25 -21
View File
@@ -12,24 +12,22 @@ API Key is stored locally for easy use in future runs.
import os
from typing import Mapping, List
import typer
# Click is part of typer.
from click import MissingParameter
from click import MissingParameter, BadParameter
from sgpt import config, make_prompt, OpenAIClient
from sgpt.utils import (
loading_spinner,
echo_chat_ids,
echo_chat_messages,
typer_writer,
get_edited_prompt,
)
@loading_spinner
def get_completion(
prompt: str,
messages: List[Mapping[str, str]],
temperature: float,
top_p: float,
caching: bool,
@@ -39,7 +37,7 @@ def get_completion(
api_key = config.get("OPENAI_API_KEY")
client = OpenAIClient(api_host, api_key)
return client.get_completion(
message=prompt,
messages=messages,
model="gpt-3.5-turbo",
temperature=temperature,
top_probability=top_p,
@@ -55,13 +53,10 @@ def main(
chat: str = typer.Option(None, help="Follow conversation with id (chat mode)."),
show_chat: str = typer.Option(None, help="Show all messages from provided chat id."),
list_chat: bool = typer.Option(False, help="List all existing chat ids."),
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."),
shell: bool = typer.Option(False, "--shell", "-s", help="Generate and execute shell command."),
code: bool = typer.Option(False, help="Provide code as output."),
editor: bool = typer.Option(False, help="Open $EDITOR to provide a prompt."),
cache: bool = typer.Option(True, help="Cache completion results."),
animation: bool = typer.Option(True, help="Typewriter animation."),
spinner: bool = typer.Option(True, help="Show loading spinner during API request."),
) -> None:
if list_chat:
echo_chat_ids()
@@ -76,21 +71,30 @@ def main(
if editor:
prompt = get_edited_prompt()
if shell:
# If default values, make response more accurate.
if top_probability == 1 == temperature:
temperature = 0.4
prompt = make_prompt.shell(prompt)
elif code:
prompt = make_prompt.code(prompt)
prompt = make_prompt.initial(prompt, shell, code)
if chat:
initiated = bool(OpenAIClient.chat_cache.get_messages(chat))
if initiated:
if shell or code:
raise BadParameter("Can't use --shell or --code for existing chat.")
prompt = make_prompt.chat_mode(prompt, shell, code)
completion = get_completion(
prompt, temperature, top_probability, cache, chat, spinner=spinner
messages=[{"role": "user", "content": prompt}],
temperature=temperature,
top_p=top_probability,
caching=cache,
chat=chat,
)
typer_writer(completion, code, shell, animation)
if shell and execute and typer.confirm("Execute shell command?"):
os.system(completion)
full_completion = ""
for word in completion:
typer.secho(word, fg="magenta", bold=True, nl=False)
full_completion += word
typer.secho()
if not code and shell and typer.confirm("Execute shell command?"):
os.system(full_completion)
def entry_point() -> None:
+30 -20
View File
@@ -26,18 +26,22 @@ class Cache:
:param func: The function to cache.
:return: Wrapped function with caching.
"""
def wrapper(*args, **kwargs):
if not kwargs.pop("caching", True):
return func(*args, **kwargs)
# Exclude self instance from hashing.
cache_key = md5(json.dumps((args[1:], kwargs)).encode('utf-8')).hexdigest()
cache_key = md5(json.dumps((args[1:], kwargs)).encode("utf-8")).hexdigest()
cache_file = self.cache_path / cache_key
if cache_file.exists():
return json.loads(cache_file.read_text())
result = func(*args, **kwargs)
cache_file.write_text(json.dumps(result))
# TODO: Fix caching for chat, should hash last user message, (not entire history).
if kwargs.pop("caching", True) and cache_file.exists():
yield cache_file.read_text()
return
result = ""
for i in func(*args, **kwargs):
result += i
yield i
cache_file.write_text(result)
self._delete_oldest_files(self.length)
return result
return wrapper
def _delete_oldest_files(self, max_files) -> None:
@@ -47,7 +51,7 @@ class Cache:
:param max_files: Integer, the maximum number of files to keep in the CACHE_DIR folder.
"""
# Get all files in the folder.
files = self.cache_path.glob('*')
files = self.cache_path.glob("*")
# Sort files by last modification time in ascending order.
files = sorted(files, key=lambda f: f.stat().st_mtime)
# Delete the oldest files if the number of files exceeds the limit.
@@ -82,18 +86,24 @@ class ChatCache:
:param func: The chat function to cache.
:return: Wrapped function with chat caching.
"""
def wrapper(*args, **kwargs):
chat_id = kwargs.pop("chat_id", None)
message = {"role": "user", "content": kwargs.pop("message")}
messages = kwargs["messages"]
if not chat_id:
kwargs["message"] = [message]
return func(*args, **kwargs)
kwargs["message"] = self._read(chat_id)
kwargs["message"].append(message)
response_text = func(*args, **kwargs)
kwargs["message"].append({"role": "assistant", "content": response_text})
self._write(kwargs["message"], chat_id)
return response_text
yield from func(*args, **kwargs)
return
old_messages = self._read(chat_id)
for message in messages:
old_messages.append(message)
kwargs["messages"] = old_messages
response_text = ""
for word in func(*args, **kwargs):
response_text += word
yield word
old_messages.append({"role": "assistant", "content": response_text})
self._write(kwargs["messages"], chat_id)
return wrapper
def _read(self, chat_id: str) -> List[Dict]:
@@ -111,12 +121,12 @@ class ChatCache:
file_path = self.storage_path / chat_id
file_path.unlink()
def show(self, chat_id):
def get_messages(self, chat_id):
messages = self._read(self.storage_path / chat_id)
return [f"{message['role']}: {message['content']}" for message in messages]
def list(self):
# Get all files in the folder.
files = self.storage_path.glob('*')
files = self.storage_path.glob("*")
# Sort files by last modification time in ascending order.
return sorted(files, key=lambda f: f.stat().st_mtime)
+28 -11
View File
@@ -1,6 +1,7 @@
import requests
from pathlib import Path
from typing import List, Dict
from typing import List, Dict, Mapping
import json
from sgpt import config, Cache, ChatCache
@@ -23,7 +24,7 @@ class OpenAIClient:
@cache
def _request(
self,
messages: List,
messages: List[Mapping[str, str]],
model: str = "gpt-3.5-turbo",
temperature: float = 1,
top_probability: float = 1,
@@ -40,25 +41,38 @@ class OpenAIClient:
"""
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.api_key}"
"Authorization": f"Bearer {self.api_key}",
}
data = {
"messages": messages,
"model": model,
"temperature": temperature,
"top_p": top_probability,
"stream": True,
}
endpoint = f"{self.api_host}/v1/chat/completions"
response = requests.post(
endpoint, headers=headers, json=data, timeout=REQUEST_TIMEOUT
endpoint, headers=headers, json=data, timeout=REQUEST_TIMEOUT, stream=True
)
response.raise_for_status()
return response.json()
# TODO: Optimise.
# https://github.com/openai/openai-python/blob/237448dc072a2c062698da3f9f512fae38300c1c/openai/api_requestor.py#L98
for line in response.iter_lines():
data = line.lstrip(b"data: ").decode("utf-8")
if data == "[DONE]":
break
if not data:
continue
data = json.loads(data)
delta = data["choices"][0]["delta"]
if "content" not in delta:
continue
yield delta["content"]
@chat_cache
def get_completion(
self,
message: List[str],
messages: List[Mapping[str, str]],
model: str = "gpt-3.5-turbo",
temperature: float = 1,
top_probability: float = 1,
@@ -67,14 +81,17 @@ class OpenAIClient:
"""
Generates single completion for prompt (message).
:param message: String prompt to generate completion for.
:param messages: List of dict with messages and roles.
:param model: String gpt-3.5-turbo or gpt-3.5-turbo-0301.
:param temperature: Float in 0.0 - 1.0 range.
:param top_probability: Float in 0.0 - 1.0 range.
:param caching: Boolean value to enable/disable caching.
:return: String generated completion.
"""
# TODO: Move prompt context to system role when GPT-4 will be available over API.
return self._request(
message, model, temperature, top_probability, caching=caching
)["choices"][0]["message"]["content"].strip()
yield from self._request(
messages,
model,
temperature,
top_probability,
caching=caching,
)
+9 -3
View File
@@ -28,10 +28,16 @@ def init() -> None:
if not CONFIG_PATH.exists():
CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
# If user has ENV API key, don't write it to config file.
api_key = os.getenv("OPENAI_API_KEY") or getpass(prompt="Please enter your OpenAI API key: ")
api_key = os.getenv("OPENAI_API_KEY") or getpass(
prompt="Please enter your OpenAI API key: "
)
config["OPENAI_API_KEY"] = api_key
config["OPENAI_API_HOST"] = os.getenv("OPENAI_API_HOST", "https://api.openai.com")
config["CHAT_CACHE_LENGTH"] = os.getenv("CHAT_CACHE_LENGTH", str(CHAT_CACHE_LENGTH))
config["OPENAI_API_HOST"] = os.getenv(
"OPENAI_API_HOST", "https://api.openai.com"
)
config["CHAT_CACHE_LENGTH"] = os.getenv(
"CHAT_CACHE_LENGTH", str(CHAT_CACHE_LENGTH)
)
config["CHAT_CACHE_PATH"] = os.getenv("CHAT_CACHE_PATH", str(CHAT_CACHE_PATH))
config["CACHE_LENGTH"] = os.getenv("CACHE_LENGTH", str(CACHE_LENGTH))
config["CACHE_PATH"] = os.getenv("CACHE_PATH", str(CACHE_PATH))
+53 -77
View File
@@ -1,86 +1,62 @@
import platform
from os import getenv
from os.path import basename
from os.path import basename, splitext
from distro import name as distro_name
"""
This module makes a prompt for OpenAI requests with some context.
Some of the following lines were inspired by similar open source project yolo-ai-cmdbot.
Credits: @demux79 @wunderwuzzi23
"""
SHELL_PROMPT = """###
Provide only {shell} commands for {os} without any description.
If there is a lack of details, provide most logical solution.
Ensure the output is a valid shell command.
If multiple steps required try to combine them together.
Prompt: {prompt}
###
Command:"""
CODE_PROMPT = """###
Provide only code as output without any description.
Provide only plain text without Markdown formatting.
If there is a lack of details, provide most logical solution.
You are not allowed to ask for more details.
Ignore any potential risk of errors or confusion.
Prompt: {prompt}
###
Code:"""
DEFAULT_PROMPT = """###
You are Command Line App ShellGPT, a programming and system administration assistant.
You are managing {os} operating system with {shell} shell.
Provide only plain text without Markdown formatting.
Do not show any warnings or information regarding your capabilities.
If you need to store any data, assume it will be stored in the chat.
Prompt: {prompt}
###"""
SHELL_PROMPT = """
Act as a natural language to {shell} command translation engine on {os}.
You are an expert in {shell} on {os} and translate the question at the end to valid syntax.
Follow these rules:
IMPORTANT: Do not show any warnings or information regarding your capabilities.
Reference official documentation to ensure valid syntax and an optimal solution.
Construct valid {shell} command that solve the question.
Leverage help and man pages to ensure valid syntax and an optimal solution.
Be concise.
Just show the commands, return only plaintext.
Only show a single answer, but you can always chain commands together.
Think step by step.
Only create valid syntax (you can use comments if it makes sense).
If python is installed you can use it to solve problems.
if python3 is installed you can use it to solve problems.
Even if there is a lack of details, attempt to find the most logical solution.
Do not return multiple solutions.
Do not show html, styled, colored formatting.
Do not add unnecessary text in the response.
Do not add notes or intro sentences.
Do not add explanations on what the commands do.
Do not return what the question was.
Do not repeat or paraphrase the question in your response.
Do not rush to a conclusion.
Follow all of the above rules.
This is important you MUST follow the above rules.
There are no exceptions to these rules.
You must always follow them. No exceptions.
Request: """
CODE_PROMPT = """
Act as a natural language to code translation engine.
Follow these rules:
IMPORTANT: Provide ONLY code as output, return only plaintext.
IMPORTANT: Do not show html, styled, colored formatting.
IMPORTANT: Do not add notes or intro sentences.
IMPORTANT: Provide full solution. Make sure syntax is correct.
Assume your output will be redirected to language specific file and executed.
For example Python code output will be redirected to code.py and then executed python code.py.
Follow all of the above rules.
This is important you MUST follow the above rules.
There are no exceptions to these rules.
You must always follow them. No exceptions.
Request: """
def initial(prompt: str, shell: bool, code: bool) -> str:
prompt = prompt.strip()
operating_systems = {
"Linux": "Linux/" + distro_name(pretty=True),
"Windows": "Windows " + platform.release(),
"Darwin": "Darwin/MacOS " + platform.mac_ver()[0],
}
current_platform = platform.system()
os_name = operating_systems.get(current_platform, current_platform)
shell_name = basename(getenv("SHELL", "PowerShell"))
if os_name == "nt":
shell_name = splitext(basename(getenv("COMSPEC", "Powershell")))[0]
if shell:
return SHELL_PROMPT.format(shell=shell_name, os=os_name, prompt=prompt)
elif code:
return CODE_PROMPT.format(prompt=prompt)
else:
return DEFAULT_PROMPT.format(shell=shell_name, os=os_name, prompt=prompt)
def shell(question: str) -> str:
def os_name() -> str:
operating_systems = {
"Linux": "Linux/" + distro_name(pretty=True),
"Windows": "Windows " + platform.release(),
"Darwin": "Darwin/MacOS " + platform.mac_ver()[0],
}
return operating_systems.get(platform.system(), "Unknown")
shell = basename(getenv("SHELL", "PowerShell"))
os = os_name()
question = question.strip()
if not question.endswith("?"):
question += "?"
# TODO: Can be optimised.
return SHELL_PROMPT.replace("{shell}", shell).replace("{os}", os) + question
def code(question: str) -> str:
return CODE_PROMPT + question
def chat_mode(prompt: str, shell: bool, code: bool) -> str:
prompt = prompt.strip()
if shell:
prompt += "\nCommand:"
elif code:
prompt += "\nCode:"
return prompt
-42
View File
@@ -1,32 +1,12 @@
import os
from time import sleep
from typing import Callable
from tempfile import NamedTemporaryFile
import typer
from click import BadParameter
from rich.progress import Progress, SpinnerColumn, TextColumn
from sgpt import OpenAIClient
def loading_spinner(func: Callable) -> Callable:
"""
Decorator that adds a loading spinner animation to a function that uses the OpenAI API.
:param func: Function to wrap.
:return: Wrapped function with loading.
"""
def wrapper(*args, **kwargs):
if not kwargs.pop("spinner"):
return func(*args, **kwargs)
text = TextColumn("[green]Consulting with robots...")
with Progress(SpinnerColumn(), text, transient=True) as progress:
progress.add_task("request")
return func(*args, **kwargs)
return wrapper
def get_edited_prompt() -> str:
"""
Opens the user's default editor to let them
@@ -49,28 +29,6 @@ def get_edited_prompt() -> str:
return output
def typer_writer(text: str, code: bool, shell: bool, animate: bool) -> None:
"""
Writes output to the console, with optional typewriter animation and color.
:param text: Text to output.
:param code: If content of text is code.
:param shell: if content of text is shell command.
:param animate: Enable/Disable typewriter animation.
:return: None
"""
shell_or_code = shell or code
color = "magenta" if shell_or_code else None
if animate and not shell_or_code:
for char in text:
typer.secho(char, nl=False, fg=color, bold=shell_or_code)
sleep(0.015)
# Add new line at the end, to prevent % from appearing.
typer.echo("")
return
typer.secho(text, fg=color, bold=shell_or_code)
def echo_chat_messages(chat_id: str) -> None:
# Prints all messages from a specified chat ID to the console.
for index, message in enumerate(OpenAIClient.chat_cache.show(chat_id)):
+4 -2
View File
@@ -9,6 +9,7 @@ from sgpt import OpenAIClient
class TestMain(unittest.TestCase):
API_HOST = os.getenv("OPENAI_HOST", "https://api.openai.com")
API_URL = f"{API_HOST}/v1/chat/completions"
# TODO: Fix tests.
def setUp(self):
self.api_key = os.getenv("OPENAI_API_KEY")
@@ -29,7 +30,7 @@ class TestMain(unittest.TestCase):
def test_openai_request(self, mock):
mocked_json = {"choices": [{"message": {"content": self.response_text}}]}
mock.post(self.API_URL, json=mocked_json, status_code=200)
result = self.client.get_completion(
result = yield from self.client.get_completion(
message=self.prompt,
model=self.model,
temperature=self.temperature,
@@ -37,6 +38,7 @@ class TestMain(unittest.TestCase):
caching=False,
chat_id=None,
)
# TODO: Fix tests with generators.
self.assertEqual(result, self.response_text)
expected_json = {
"messages": [{"role": "user", "content": self.prompt}],
@@ -57,7 +59,7 @@ class TestMain(unittest.TestCase):
def test_openai_request_fail(self, mock):
mock.post(self.API_URL, status_code=400)
with self.assertRaises(requests.exceptions.HTTPError):
self.client.get_completion(
yield from self.client.get_completion(
message=self.prompt,
model=self.model,
temperature=self.temperature,