Release 0.7.0 chat mode, caching, improvements

This commit is contained in:
Farkhod Sadykov
2023-03-04 22:21:34 +01:00
committed by Farkhod Sadykov
parent eb20a1356b
commit ed33f83eca
11 changed files with 440 additions and 69 deletions
+1 -1
View File
@@ -39,4 +39,4 @@ jobs:
black --target-version py310 -l 120 *.py
- name: Run unittests
run: |
python -m unittest unittests.py
python -m unittest tests/unittests.py
+76 -20
View File
@@ -115,30 +115,86 @@ python fizz_buzz.py
# Fizz
# ...
```
### Chat
To start a chat session, use the `--chat` option followed by a unique session name and a prompt:
```shell
sgpt --chat number "please remember my favorite number: 4"
# -> I will remember that your favorite number is 4.
sgpt --chat number "what would be my favorite number + 4?"
# -> Your favorite number is 4, so if we add 4 to it, the result would be 8.
```
You can also use chat sessions to iteratively improve ChatGPT's suggestions by providing additional clues.
```shell
sgpt --chat python_requst --code "make an example request to localhost using Python"
```
```python
import requests
response = requests.get('http://localhost')
print(response.text)
```
Asking ChatGPT to add a cache to our request.
```shell
sgpt --chat python_request --code "add caching"
```
```python
import requests
from cachecontrol import CacheControl
sess = requests.session()
cached_sess = CacheControl(sess)
response = cached_sess.get('http://localhost')
print(response.text)
```
### Chat sessions
To list all the current chat sessions, use the `--list-chat` option:
```shell
sgpt --list-chat
# .../shell_gpt/chat_cache/number
# .../shell_gpt/chat_cache/python_request
```
To show all the messages related to a specific chat session, use the `--show-chat` option followed by the session name:
```shell
sgpt --show-chat number
# 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.
```
### Request cache
Control cache using `--cache` (default) and `--no-cache` options. This caching applies for all `sgpt` requests to OpenAI API:
```shell
sgpt "what are the colors of a rainbow"
# -> The colors of a rainbow are red, orange, yellow, green, blue, indigo, and violet.
```
Next time, same exact query will get results from local cache instantly. Note that `sgpt "what are the colors of a rainbow" --temperature 0.5` will make a new request, since we didn't provide `--temperature` (same applies to `--top-probability`) on previous request.
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 ────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ --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. │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─ 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] │
│ --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. │
│ --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. │
╰───────────────────────────────────────────────────────────────────────────────────────────────────────────╯
```
## Docker
+1 -1
View File
@@ -49,7 +49,7 @@ else
exit 1
fi
if python -m unittest unittests.py
if python -m unittest tests/unittests.py
then
echo 'Unittests passed ✅'
else
+2 -5
View File
@@ -3,18 +3,15 @@ from setuptools import setup, find_packages
# pylint: disable=consider-using-with
setup(
name="shell_gpt",
version="0.6.0",
version="0.7.0",
packages=find_packages(),
py_modules=[
"sgpt",
],
install_requires=[
"typer~=0.7.0",
"requests~=2.28.2",
"rich==13.3.1",
],
entry_points={
"console_scripts": ["sgpt = sgpt:entry_point"],
"console_scripts": ["sgpt = sgpt:cli"],
},
author="Farkhod Sadykov",
author_email="farkhod@sadykov.dev",
+3
View File
@@ -0,0 +1,3 @@
from .chat_gpt import ChatGPT
from .app import main as main
from .app import entry_point as cli
+3
View File
@@ -0,0 +1,3 @@
from .app import entry_point
entry_point()
+114 -32
View File
@@ -17,21 +17,29 @@ from time import sleep
from pathlib import Path
from getpass import getpass
from tempfile import NamedTemporaryFile
from typing import Callable
import typer
import requests
# Click is part of typer.
from click import MissingParameter, BadParameter
from rich.progress import Progress, SpinnerColumn, TextColumn
from sgpt import ChatGPT
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"
CURRENT_SHELL = "PowerShell" if platform.system() == "Windows" else "Bash"
CODE_PROMPT = "Provide code and only code as output without any additional text, prompt or note."
SHELL_PROMPT = f"Provide only {CURRENT_SHELL} command as output, without any additional text or prompt."
def get_api_key():
def get_api_key() -> str:
"""
Retrieves API key from the file located in the user's home
directory, or prompts the user to input it if it does not exist.
:return: String API key for OpenAI API requests.
"""
if not KEY_FILE.exists():
api_key = getpass(prompt="Please enter your API secret key")
KEY_FILE.parent.mkdir(parents=True, exist_ok=True)
@@ -41,7 +49,13 @@ def get_api_key():
return api_key
def loading_spinner(func):
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)
@@ -49,11 +63,16 @@ def loading_spinner(func):
with Progress(SpinnerColumn(), text, transient=True) as progress:
progress.add_task("request")
return func(*args, **kwargs)
return wrapper
def get_edited_prompt():
def get_edited_prompt() -> str:
"""
Opens the user's default editor to let them
input a prompt, and returns the edited text.
:return: String prompt.
"""
with NamedTemporaryFile(suffix=".txt", delete=False) as file:
# Create file and store path.
file_path = file.name
@@ -70,20 +89,44 @@ def get_edited_prompt():
@loading_spinner
def openai_request(prompt, api_key, temperature, top_p):
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {api_key}"}
data = {
"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=30)
response.raise_for_status()
return response.json()["choices"][0]["message"]["content"]
def get_completion(
prompt: str,
api_key: str,
temperature: float,
top_p: float,
caching: bool,
chat: str,
) -> str:
"""
Generates completions for a given prompt using the OpenAI API.
:param prompt: Prompt to generate completion for.
:param api_key: OpenAI API key.
:param temperature: Controls randomness of GPT-3.5 completions.
:param top_p: Controls most probable tokens for completions.
:param caching: Enable/Disable caching.
:param chat: Enable/Disable conversation (chat mode).
:return: GPT-3.5 generated completion.
"""
chat_gpt = ChatGPT(api_key)
model = "gpt-3.5-turbo"
if not chat:
return chat_gpt.get_completion(prompt, model, temperature, top_p, caching)
return chat_gpt.get_chat_completion(
model=model, temperature=temperature, top_probability=top_p, message=prompt, chat_id=chat
)
def typer_writer(text, code, shell, animate):
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:
@@ -96,36 +139,69 @@ def typer_writer(text, code, shell, animate):
typer.secho(text, fg=color, bold=shell_or_code)
def echo_chat_messages(chat_id: str) -> None:
"""
Writes all messages from a specified chat ID to the console.
:param chat_id: String chat id.
:return: None
"""
for index, message in enumerate(ChatGPT.chat_cache.get_messages(chat_id)):
color = "cyan" if index % 2 == 0 else "green"
typer.secho(message, fg=color)
def echo_chat_ids() -> None:
"""
Writes all existing chat IDs to the console.
:return: None
"""
for chat_id in ChatGPT.chat_cache.get_chats():
typer.echo(chat_id)
# 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."),
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)."),
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."),
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."),
):
api_key = get_api_key()
) -> None:
if list_chat:
echo_chat_ids()
return
if show_chat:
echo_chat_messages(show_chat)
if not prompt and not editor:
raise MissingParameter(param_hint="PROMPT", param_type="string")
if editor:
prompt = get_edited_prompt()
if shell:
# 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"""Provide only {current_shell} command as output, without any additional text or prompt.
{prompt}"""
prompt = f"{SHELL_PROMPT} {prompt}"
elif code:
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, api_key, temperature, top_probability, spinner=spinner)
# For some reason OpenAI returns several leading/trailing white spaces.
response_text = response_text.strip()
prompt = f"{CODE_PROMPT} {prompt}"
api_key = get_api_key()
response_text = get_completion(
prompt, api_key, temperature, top_probability, cache, chat, spinner=spinner
)
if code:
# Responses from GPT-3.5 wrapped into Markdown code block.
lines = response_text.split("\n")
@@ -134,12 +210,18 @@ def main(
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)
def entry_point():
def entry_point() -> None:
"""
Python package entry point defined in setup.py
:return: None
"""
typer.run(main)
+228
View File
@@ -0,0 +1,228 @@
import requests
import json
from hashlib import md5
from pathlib import Path
from tempfile import gettempdir
from typing import List, Dict, Callable
class Cache:
"""
Decorator class that adds caching functionality to a function.
"""
CACHE_DIR = Path(gettempdir()) / "shell_gpt" / "cache"
def __init__(self, length: int):
"""
Initialize the Cache decorator.
:param length: Integer, maximum number of cache files to keep.
"""
self.length = length
def __call__(self, func: Callable) -> Callable:
"""
The Cache decorator.
: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)
cache_dir = self.CACHE_DIR
# Exclude self (ChatGPT) instance from hashing.
cache_key = md5(json.dumps((args[1:], kwargs)).encode('utf-8')).hexdigest()
cache_file = cache_dir / cache_key
if cache_file.exists():
return json.loads(cache_file.read_text())
result = func(*args, **kwargs)
cache_file.parent.mkdir(parents=True, exist_ok=True)
cache_file.write_text(json.dumps(result))
self.__delete_oldest_files(self.length)
return result
return wrapper
@classmethod
def __delete_oldest_files(cls, max_files) -> None:
"""
Class method to delete the oldest cached files in the CACHE_DIR folder.
:param max_files: Integer, the maximum number of files to keep in the CACHE_DIR folder.
"""
# Get all files in the folder.
files = cls.CACHE_DIR.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.
if len(files) > max_files:
num_files_to_delete = len(files) - max_files
for i in range(num_files_to_delete):
files[i].unlink()
class ChatCache:
"""
This class is used as a decorator for OpenAI chat API requests.
The ChatCache class caches chat messages and keeps track of the
conversation history. It is designed to store cached messages
in a specified directory and in JSON format.
"""
CACHE_DIR = Path(gettempdir()) / "shell_gpt" / "chat_cache"
CACHE_FILE_MAIN = CACHE_DIR / "main_cache.json"
def __init__(self, length: int):
"""
Initialize the ChatCache decorator.
:param length: Integer, maximum number of cached messages to keep.
"""
self.length = length
def __call__(self, func: Callable) -> Callable:
"""
The Cache decorator.
:param func: The chat function to cache.
:return: Wrapped function with chat caching.
"""
def wrapper(*args, **kwargs):
chat_id = kwargs.pop("chat_id", None)
file_path = self.CACHE_DIR / chat_id if chat_id else self.CACHE_FILE_MAIN
message = {"role": "user", "content": kwargs.pop("message")}
kwargs["messages"] = self.read(file_path)
kwargs["messages"].append(message)
response_text = func(*args, **kwargs)
kwargs["messages"].append({"role": "assistant", "content": response_text})
self.write(kwargs["messages"], self.length, file_path)
return response_text
return wrapper
@classmethod
def read(cls, file_path: Path) -> List[Dict]:
if not file_path.exists():
return []
parsed_cache = json.loads(file_path.read_text())
if isinstance(parsed_cache, list):
return parsed_cache
return []
@classmethod
def write(cls, messages: List[Dict], length: int, file_path: Path):
file_path.parent.mkdir(parents=True, exist_ok=True)
json.dump(messages[-length:], file_path.open("w"))
@classmethod
def invalidate(cls, chat_id: str):
file_path = cls.CACHE_DIR / chat_id
file_path.unlink()
@classmethod
def get_messages(cls, chat_id):
messages = cls.read(cls.CACHE_DIR / chat_id)
return [f"{message['role']}: {message['content']}" for message in messages]
@classmethod
def get_chats(cls):
# Get all files in the folder.
files = cls.CACHE_DIR.glob('*')
# Sort files by last modification time in ascending order.
return sorted(files, key=lambda f: f.stat().st_mtime)
class ChatGPT:
"""
OpenAI ChatGPT API interface.
"""
API_URL = "https://api.openai.com/v1/chat/completions"
TEMP_FILE = Path(gettempdir()) / "shell_gpt_cache.json"
chat_cache = ChatCache(length=50)
cache = Cache(length=200)
def __init__(self, api_key: str):
"""
Initialize ChatGPT.
:param api_key: OpenAI API key.
"""
self.api_key = api_key
@cache
def __request(
self,
messages: List,
model: str = "gpt-3.5-turbo",
temperature: float = 1,
top_probability: float = 1,
) -> Dict:
"""
Make request to OpenAI ChatGPT API, read more:
https://platform.openai.com/docs/api-reference/chat
:param messages: List of messages {"role": user or assistant, "content": message_string}
: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.
:return: Response body JSON.
"""
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {self.api_key}"}
data = {
"messages": messages,
"model": model,
"temperature": temperature,
"top_p": top_probability,
}
response = requests.post(self.API_URL, headers=headers, json=data, timeout=30)
response.raise_for_status()
return response.json()
def get_completion(
self,
message: str,
model: str = "gpt-3.5-turbo",
temperature: float = 1,
top_probability: float = 1,
caching: bool = True,
) -> str:
"""
Generates single completion for prompt (message).
:param message: String prompt to generate completion for.
: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.
"""
message = {"role": "user", "content": message}
return self.__request(
[message], model, temperature, top_probability, caching=caching
)["choices"][0]["message"]["content"].strip()
@chat_cache
def get_chat_completion(
self,
messages: List[Dict],
model: str = "gpt-3.5-turbo",
temperature: float = 1,
top_probability: float = 1
) -> str:
"""
Generate completion based on conversation. Note that this method
should be used with ChatCache decorator, which will handle caching
of messages. In this case messages parameter can be ignored, instead
use just message argument. e.g: get_chat_completion(message="anything").
:param messages: List of dialog messages, comes from caching decorator.
: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.
:return: String generated completion for last user message.
"""
# It returns several leading/trailing whitespaces.
return self.__request(
messages, model, temperature, top_probability
)["choices"][0]["message"]["content"].strip()
View File
+12 -10
View File
@@ -1,10 +1,12 @@
import unittest
import requests_mock
import requests
import sgpt
from sgpt import ChatGPT
class TestMain(unittest.TestCase):
API_URL = ChatGPT.API_URL
def setUp(self):
self.prompt = "What is the capital of France?"
self.shell = False
@@ -16,12 +18,16 @@ class TestMain(unittest.TestCase):
self.temperature = 1.0
self.top_p = 1.0
self.response_text = "Paris"
self.model = "gpt-3.5-turbo"
self.chat_gpt = ChatGPT(self.api_key)
@requests_mock.Mocker()
def test_openai_request(self, mock):
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)
mock.post(self.API_URL, json=mocked_json, status_code=200)
result = self.chat_gpt.get_completion(
self.prompt, self.model, self.temperature, self.top_p, caching=False
)
self.assertEqual(result, self.response_text)
expected_json = {
"messages": [{"role": "user", "content": self.prompt}],
@@ -37,14 +43,10 @@ class TestMain(unittest.TestCase):
@requests_mock.Mocker()
def test_openai_request_fail(self, mock):
mock.post(sgpt.API_URL, status_code=400)
mock.post(self.API_URL, status_code=400)
with self.assertRaises(requests.exceptions.HTTPError):
sgpt.openai_request(
self.prompt,
self.api_key,
self.temperature,
self.top_p,
spinner=self.spinner,
self.chat_gpt.get_completion(
self.prompt, self.model, self.temperature, self.top_p, caching=False
)