mirror of
https://github.com/TheR1D/shell_gpt.git
synced 2026-07-03 14:10:18 +02:00
Runtime config, code and file structure improvements, GitHub action fixes
This commit is contained in:
@@ -1,6 +1,12 @@
|
||||
name: Run linters and unittests
|
||||
|
||||
on: [push]
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
lint_test:
|
||||
@@ -39,4 +45,5 @@ jobs:
|
||||
black --target-version py310 -l 120 *.py
|
||||
- name: Run unittests
|
||||
run: |
|
||||
export OPENAI_API_KEY=test_api_key
|
||||
python -m unittest tests/unittests.py
|
||||
|
||||
@@ -11,7 +11,7 @@ pip install shell-gpt
|
||||
```
|
||||
You'll need an OpenAI API key, you can generate one [here](https://beta.openai.com/account/api-keys).
|
||||
|
||||
If the`$OPENAI_API_KEY` environment variable is set it will be used, otherwise, you will be prompted for your key which will then be stored in `~/.config/shell-gpt/api_key.txt`.
|
||||
If the`$OPENAI_API_KEY` environment variable is set it will be used, otherwise, you will be prompted for your key which will then be stored in `~/.config/shell_gpt/.sgptrc`.
|
||||
|
||||
## Usage
|
||||
`sgpt` has a variety of use cases, including simple queries, shell queries, and code queries.
|
||||
@@ -199,6 +199,24 @@ Next time, same exact query will get results from local cache instantly. Note th
|
||||
|
||||
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.
|
||||
|
||||
### Runtime configuration file
|
||||
You can setup some parameters in runtime configuration file `~/.config/shell_gpt/.sgptrc`:
|
||||
```text
|
||||
# API key, also it is possible to define OPENAI_API_KEY env.
|
||||
OPENAI_API_KEY=your_api_key
|
||||
# OpenAI host, useful if you would like to use proxy.
|
||||
OPENAI_API_HOST=https://api.openai.com
|
||||
# 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
|
||||
```
|
||||
|
||||
### Full list of arguments
|
||||
```shell
|
||||
|
||||
@@ -3,7 +3,7 @@ from setuptools import setup, find_packages
|
||||
# pylint: disable=consider-using-with
|
||||
setup(
|
||||
name="shell_gpt",
|
||||
version="0.7.1",
|
||||
version="0.7.3",
|
||||
packages=find_packages(),
|
||||
install_requires=[
|
||||
"typer~=0.7.0",
|
||||
|
||||
+5
-1
@@ -1,4 +1,8 @@
|
||||
from .chat_gpt import ChatGPT
|
||||
from . import config as config
|
||||
from .cache import Cache as Cache
|
||||
from .cache import ChatCache as ChatCache
|
||||
from .client import OpenAIClient as OpenAIClient
|
||||
from . import utils as utils
|
||||
from .app import main as main
|
||||
from .app import entry_point as cli
|
||||
from . import make_prompt as make_prompt
|
||||
|
||||
+27
-150
@@ -12,161 +12,42 @@ API Key is stored locally for easy use in future runs.
|
||||
|
||||
|
||||
import os
|
||||
import platform
|
||||
from time import sleep
|
||||
from pathlib import Path
|
||||
from getpass import getpass
|
||||
from tempfile import NamedTemporaryFile
|
||||
from typing import Callable
|
||||
|
||||
import typer
|
||||
|
||||
# Click is part of typer.
|
||||
from click import MissingParameter, BadParameter
|
||||
from rich.progress import Progress, SpinnerColumn, TextColumn
|
||||
from sgpt import ChatGPT
|
||||
from sgpt import make_prompt
|
||||
|
||||
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() -> 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 "OPENAI_API_KEY" in os.environ:
|
||||
return os.environ["OPENAI_API_KEY"]
|
||||
|
||||
if not KEY_FILE.exists():
|
||||
api_key = getpass(prompt="Please enter your API secret key")
|
||||
KEY_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
KEY_FILE.write_text(api_key)
|
||||
else:
|
||||
api_key = KEY_FILE.read_text().strip()
|
||||
return api_key
|
||||
|
||||
|
||||
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
|
||||
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
|
||||
editor = os.environ.get("EDITOR", "vim")
|
||||
# This will write text to file using $EDITOR.
|
||||
os.system(f"{editor} {file_path}")
|
||||
# Read file when editor is closed.
|
||||
with open(file_path, "r") as file:
|
||||
output = file.read()
|
||||
os.remove(file_path)
|
||||
if not output:
|
||||
raise BadParameter("Couldn't get valid PROMPT from $EDITOR")
|
||||
return output
|
||||
from click import MissingParameter
|
||||
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,
|
||||
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
|
||||
):
|
||||
api_host = config.get("OPENAI_API_HOST")
|
||||
api_key = config.get("OPENAI_API_KEY")
|
||||
client = OpenAIClient(api_host, api_key)
|
||||
return client.get_completion(
|
||||
message=prompt,
|
||||
model="gpt-3.5-turbo",
|
||||
temperature=temperature,
|
||||
top_probability=top_p,
|
||||
caching=caching,
|
||||
chat_id=chat,
|
||||
)
|
||||
|
||||
|
||||
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:
|
||||
"""
|
||||
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."),
|
||||
@@ -187,6 +68,7 @@ def main(
|
||||
return
|
||||
if show_chat:
|
||||
echo_chat_messages(show_chat)
|
||||
return
|
||||
|
||||
if not prompt and not editor:
|
||||
raise MissingParameter(param_hint="PROMPT", param_type="string")
|
||||
@@ -195,29 +77,24 @@ def main(
|
||||
prompt = get_edited_prompt()
|
||||
|
||||
if shell:
|
||||
# If probability and temperature were not changed (default), make response more accurate.
|
||||
# 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)
|
||||
|
||||
api_key = get_api_key()
|
||||
response_text = get_completion(
|
||||
prompt, api_key, temperature, top_probability, cache, chat, spinner=spinner
|
||||
completion = get_completion(
|
||||
prompt, temperature, top_probability, cache, chat, spinner=spinner
|
||||
)
|
||||
|
||||
typer_writer(response_text, code, shell, animation)
|
||||
typer_writer(completion, code, shell, animation)
|
||||
if shell and execute and typer.confirm("Execute shell command?"):
|
||||
os.system(response_text)
|
||||
os.system(completion)
|
||||
|
||||
|
||||
def entry_point() -> None:
|
||||
"""
|
||||
Python package entry point defined in setup.py
|
||||
|
||||
:return: None
|
||||
"""
|
||||
# Python package entry point defined in setup.py
|
||||
typer.run(main)
|
||||
|
||||
|
||||
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
import json
|
||||
from hashlib import md5
|
||||
from pathlib import Path
|
||||
from typing import List, Dict, Callable
|
||||
|
||||
|
||||
class Cache:
|
||||
"""
|
||||
Decorator class that adds caching functionality to a function.
|
||||
"""
|
||||
|
||||
def __init__(self, length: int, cache_path: Path) -> None:
|
||||
"""
|
||||
Initialize the Cache decorator.
|
||||
|
||||
:param length: Integer, maximum number of cache files to keep.
|
||||
"""
|
||||
self.length = length
|
||||
self.cache_path = cache_path
|
||||
self.cache_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
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)
|
||||
# Exclude self instance from hashing.
|
||||
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))
|
||||
self._delete_oldest_files(self.length)
|
||||
return result
|
||||
return wrapper
|
||||
|
||||
def _delete_oldest_files(self, 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 = 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.
|
||||
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.
|
||||
"""
|
||||
|
||||
def __init__(self, length: int, storage_path: Path):
|
||||
"""
|
||||
Initialize the ChatCache decorator.
|
||||
|
||||
:param length: Integer, maximum number of cached messages to keep.
|
||||
"""
|
||||
self.length = length
|
||||
self.storage_path = storage_path
|
||||
self.storage_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
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)
|
||||
message = {"role": "user", "content": kwargs.pop("message")}
|
||||
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
|
||||
return wrapper
|
||||
|
||||
def _read(self, chat_id: str) -> List[Dict]:
|
||||
file_path = self.storage_path / chat_id
|
||||
if not file_path.exists():
|
||||
return []
|
||||
parsed_cache = json.loads(file_path.read_text())
|
||||
return parsed_cache if isinstance(parsed_cache, list) else []
|
||||
|
||||
def _write(self, messages: List[Dict], chat_id: str):
|
||||
file_path = self.storage_path / chat_id
|
||||
json.dump(messages[-self.length:], file_path.open("w"))
|
||||
|
||||
def invalidate(self, chat_id: str):
|
||||
file_path = self.storage_path / chat_id
|
||||
file_path.unlink()
|
||||
|
||||
def show(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('*')
|
||||
# Sort files by last modification time in ascending order.
|
||||
return sorted(files, key=lambda f: f.stat().st_mtime)
|
||||
@@ -1,229 +0,0 @@
|
||||
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.
|
||||
"""
|
||||
# TODO: Move prompt context to system role when GPT-4 will be available over API.
|
||||
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()
|
||||
@@ -0,0 +1,80 @@
|
||||
import requests
|
||||
from pathlib import Path
|
||||
from typing import List, Dict
|
||||
|
||||
from sgpt import config, Cache, ChatCache
|
||||
|
||||
|
||||
CHAT_CACHE_LENGTH = int(config.get("CHAT_CACHE_LENGTH"))
|
||||
CHAT_CACHE_PATH = Path(config.get("CHAT_CACHE_PATH"))
|
||||
CACHE_LENGTH = int(config.get("CACHE_LENGTH"))
|
||||
CACHE_PATH = Path(config.get("CACHE_PATH"))
|
||||
REQUEST_TIMEOUT = int(config.get("REQUEST_TIMEOUT"))
|
||||
|
||||
|
||||
class OpenAIClient:
|
||||
cache = Cache(CACHE_LENGTH, CACHE_PATH)
|
||||
chat_cache = ChatCache(CHAT_CACHE_LENGTH, CHAT_CACHE_PATH)
|
||||
|
||||
def __init__(self, api_host: str, api_key: str) -> None:
|
||||
self.api_key = api_key
|
||||
self.api_host = api_host
|
||||
|
||||
@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,
|
||||
}
|
||||
endpoint = f"{self.api_host}/v1/chat/completions"
|
||||
response = requests.post(
|
||||
endpoint, headers=headers, json=data, timeout=REQUEST_TIMEOUT
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
@chat_cache
|
||||
def get_completion(
|
||||
self,
|
||||
message: List[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.
|
||||
"""
|
||||
# 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()
|
||||
@@ -0,0 +1,71 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
from getpass import getpass
|
||||
from tempfile import gettempdir
|
||||
|
||||
from click import UsageError
|
||||
|
||||
CONFIG_FOLDER = os.path.expanduser("~/.config")
|
||||
CONFIG_PATH = Path(CONFIG_FOLDER) / "shell_gpt" / ".sgptrc"
|
||||
CHAT_CACHE_PATH = Path(gettempdir()) / "shell_gpt" / "chat_cache"
|
||||
CACHE_PATH = Path(gettempdir()) / "shell_gpt" / "cache"
|
||||
CHAT_CACHE_LENGTH = 100
|
||||
CACHE_LENGTH = 100
|
||||
REQUEST_TIMEOUT = 60
|
||||
EXPECTED_KEYS = (
|
||||
"OPENAI_API_HOST",
|
||||
"OPENAI_API_KEY",
|
||||
"CHAT_CACHE_LENGTH",
|
||||
"CHAT_CACHE_PATH",
|
||||
"CACHE_LENGTH",
|
||||
"CACHE_PATH",
|
||||
"REQUEST_TIMEOUT",
|
||||
)
|
||||
config = {}
|
||||
|
||||
|
||||
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: ")
|
||||
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["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))
|
||||
config["REQUEST_TIMEOUT"] = os.getenv("REQUEST_TIMEOUT", str(REQUEST_TIMEOUT))
|
||||
_write()
|
||||
|
||||
with open(CONFIG_PATH, "r") as file:
|
||||
for line in file:
|
||||
if "=" in line:
|
||||
key, value = line.strip().split("=")
|
||||
config[key] = value
|
||||
|
||||
|
||||
def get(key: str) -> str:
|
||||
# Prioritize ENV variables.
|
||||
value = os.getenv(key) or config.get(key)
|
||||
assert value, UsageError(f"Config missing: {key}.")
|
||||
return value
|
||||
|
||||
|
||||
def _write() -> None:
|
||||
with open(CONFIG_PATH, "w") as file:
|
||||
for key, value in config.items():
|
||||
# Write only keys which are not presented in ENV.
|
||||
if key in os.environ:
|
||||
continue
|
||||
file.write(f"{key}={value}\n")
|
||||
|
||||
|
||||
def put(key: str, value: str, write_file=True) -> None:
|
||||
config[key] = value
|
||||
if not write_file:
|
||||
return
|
||||
_write()
|
||||
|
||||
|
||||
init()
|
||||
@@ -0,0 +1,84 @@
|
||||
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
|
||||
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
|
||||
editor = os.environ.get("EDITOR", "vim")
|
||||
# This will write text to file using $EDITOR.
|
||||
os.system(f"{editor} {file_path}")
|
||||
# Read file when editor is closed.
|
||||
with open(file_path, "r") as file:
|
||||
output = file.read()
|
||||
os.remove(file_path)
|
||||
if not output:
|
||||
raise BadParameter("Couldn't get valid PROMPT from $EDITOR")
|
||||
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)):
|
||||
color = "cyan" if index % 2 == 0 else "green"
|
||||
typer.secho(message, fg=color)
|
||||
|
||||
|
||||
def echo_chat_ids() -> None:
|
||||
# Prints all existing chat IDs to the console.
|
||||
for chat_id in OpenAIClient.chat_cache.list():
|
||||
typer.echo(chat_id)
|
||||
@@ -1,7 +1,8 @@
|
||||
"""
|
||||
This test module will execute real commands using shell.
|
||||
This means it will call sgpt.py with command line arguments.
|
||||
Make sure you have your API key in place ~/.config/shell-gpt/api_key.txt
|
||||
Make sure you have your API key in place ~/.config/shell_gpt/.sgptrc
|
||||
or ENV variable OPENAI_API_KEY.
|
||||
It is useful for quick tests, saves a bit time.
|
||||
"""
|
||||
|
||||
|
||||
+26
-9
@@ -1,32 +1,41 @@
|
||||
import os
|
||||
import unittest
|
||||
import requests_mock
|
||||
import requests
|
||||
from sgpt import ChatGPT
|
||||
|
||||
from sgpt import OpenAIClient
|
||||
|
||||
|
||||
class TestMain(unittest.TestCase):
|
||||
API_URL = ChatGPT.API_URL
|
||||
API_HOST = os.getenv("OPENAI_HOST", "https://api.openai.com")
|
||||
API_URL = f"{API_HOST}/v1/chat/completions"
|
||||
|
||||
def setUp(self):
|
||||
self.api_key = os.getenv("OPENAI_API_KEY")
|
||||
assert self.api_key, "OPENAI_API_KEY ENV is required."
|
||||
self.prompt = "What is the capital of France?"
|
||||
self.shell = False
|
||||
self.execute = False
|
||||
self.code = False
|
||||
self.animation = True
|
||||
self.spinner = True
|
||||
self.api_key = "test-api-key"
|
||||
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)
|
||||
self.client = OpenAIClient(self.API_HOST, self.api_key)
|
||||
|
||||
@requests_mock.Mocker()
|
||||
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.chat_gpt.get_completion(
|
||||
self.prompt, self.model, self.temperature, self.top_p, caching=False
|
||||
result = self.client.get_completion(
|
||||
message=self.prompt,
|
||||
model=self.model,
|
||||
temperature=self.temperature,
|
||||
top_probability=self.top_p,
|
||||
caching=False,
|
||||
chat_id=None,
|
||||
)
|
||||
self.assertEqual(result, self.response_text)
|
||||
expected_json = {
|
||||
@@ -35,7 +44,10 @@ class TestMain(unittest.TestCase):
|
||||
"temperature": self.temperature,
|
||||
"top_p": self.top_p,
|
||||
}
|
||||
expected_headers = {"Content-Type": "application/json", "Authorization": f"Bearer {self.api_key}"}
|
||||
expected_headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
}
|
||||
request = mock.request_history[0]
|
||||
self.assertEqual(request.json(), expected_json)
|
||||
for key, value in expected_headers.items():
|
||||
@@ -45,8 +57,13 @@ 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.chat_gpt.get_completion(
|
||||
self.prompt, self.model, self.temperature, self.top_p, caching=False
|
||||
self.client.get_completion(
|
||||
message=self.prompt,
|
||||
model=self.model,
|
||||
temperature=self.temperature,
|
||||
top_probability=self.top_p,
|
||||
caching=False,
|
||||
chat_id=None
|
||||
)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user