mirror of
https://github.com/TheR1D/shell_gpt.git
synced 2026-07-03 14:10:18 +02:00
Migrating to TOML new linting and stricted typing (#165)
* pyproject.toml * sdist and bdist specific files. * CONTRIBUITNG.md. * New linters and CI/CD. * Mypy stricted types. * Shell scripts to run linters and tests.
This commit is contained in:
@@ -23,26 +23,16 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install pylint
|
||||
pip install black
|
||||
pip install requests_mock
|
||||
pip install -r requirements.txt
|
||||
- name: Analysing the code with pylint
|
||||
run: |
|
||||
pylint \
|
||||
./sgpt \
|
||||
./tests \
|
||||
--disable=fixme \
|
||||
--disable=cyclic-import \
|
||||
--disable=useless-import-alias \
|
||||
--disable=missing-function-docstring \
|
||||
--disable=missing-module-docstring \
|
||||
--disable=missing-class-docstring \
|
||||
--disable=too-many-function-args \
|
||||
|
||||
- name: Analysing the code with black
|
||||
run: black ./sgpt ./tests --check --target-version py310
|
||||
- name: Run unittests
|
||||
pip install ."[dev,test]"
|
||||
- name: black
|
||||
run: black sgpt tests --check
|
||||
- name: isort
|
||||
run: isort sgpt tests scripts --check-only
|
||||
- name: ruff
|
||||
run: ruff sgpt tests scripts
|
||||
- name: mypy
|
||||
run: mypy sgpt
|
||||
- name: unittests
|
||||
run: |
|
||||
export OPENAI_API_KEY=test_api_key
|
||||
python -m unittest tests/unittests.py
|
||||
pytest tests/test_unit.py
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
# Contributing to ShellGPT
|
||||
Thank you for considering contributing to ShellGPT (sgpt)! In order to ensure a smooth and enjoyable experience for everyone, please follow the steps outlined below.
|
||||
|
||||
## Find an issue to work on
|
||||
* First, browse the existing issues to find one that interests you. If you find an issue you would like to work on, assign it to yourself and leave a comment expressing your interest in working on it soon.
|
||||
* If you have a new feature in mind that doesn't have an existing issue, kindly create a discussion in the "ideas" category using GitHub Discussions. Gather feedback from the community, and if you receive approval from at least a couple of people, create an issue and assign it to yourself.
|
||||
* If there is an urgent issue, such as a critical bug causing the app to crash, create a pull request right away.
|
||||
|
||||
## Developing
|
||||
> ShellGPT is written using strict types, which means you will need to define types. The project utilizes several linting and testing tools: ruff, mypy, isort, black, and pytest.
|
||||
|
||||
### Virtual environment
|
||||
Create a virtual environment using Python venv and activate it:
|
||||
|
||||
```shell
|
||||
python -m venv env && source ./env/bin/activate
|
||||
```
|
||||
|
||||
### Install dependencies
|
||||
Install the necessary dependencies, in this case you will need to install the development and test dependencies:
|
||||
|
||||
```shell
|
||||
pip install -e ."[dev,test]"
|
||||
```
|
||||
### Start coding
|
||||
With your environment set up and the issue assigned, you can begin working on your solution. Familiarize yourself with the existing codebase, and follow the project's coding style and conventions. Remember to write clean, modular, and maintainable code, which will make it easier for others to understand and review. As you make progress, commit your changes frequently to keep track of your work.
|
||||
|
||||
### Testing
|
||||
This is very important step. Every changes that implements a new feature or modifies the logic of existing features should include "integration" tests. These are tests that call `sgpt` with defined arguments, capture the output, and verify that the feature works as expected. See `test_integration.py` for examples. The tests should be easy to read and understand.
|
||||
|
||||
### Pull request
|
||||
Before creating a pull request, ensure that you run `scripts/lint.sh` and `scripts/tests.sh`. All linters and tests should pass. In the pull request, provide a high-level description of your changes and step-by-step instructions on how to test them. Include any necessary commands.
|
||||
|
||||
### Code review
|
||||
Once you've submitted your pull request, it's time for code review. Be patient and open to feedback from the reviewers. Address any concerns they may have and work collaboratively to improve the code. Together, we can make ShellGPT an even better project.
|
||||
|
||||
Thank you once again for your contribution! We're excited to have you on board.
|
||||
@@ -17,4 +17,3 @@ USER app
|
||||
VOLUME /tmp/shell_gpt
|
||||
|
||||
ENTRYPOINT ["sgpt"]
|
||||
|
||||
|
||||
-59
@@ -1,59 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
chmod +x "$PWD/pre-push.sh"
|
||||
ln -sf "$PWD/pre-push.sh" .git/hooks/pre-push
|
||||
|
||||
# Check if pylint is installed
|
||||
if ! command -v pylint > /dev/null; then
|
||||
echo "pylint is not installed. Install it with 'pip install pylint'"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check if black is installed
|
||||
if ! command -v black > /dev/null; then
|
||||
echo "black is not installed. Install it with 'pip install black'"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo 'Executing pre-push hook.'
|
||||
|
||||
if [ -f "$PWD/venv/bin/activate" ]; then
|
||||
source $PWD/venv/bin/activate
|
||||
fi
|
||||
|
||||
if black ./sgpt ./tests --check --target-version py310
|
||||
then
|
||||
echo 'Black passed ✅'
|
||||
else
|
||||
echo 'Black failed ❌'
|
||||
echo 'RUN: black ./sgpt ./tests --target-version py310'
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if pylint \
|
||||
./sgpt \
|
||||
./tests \
|
||||
--disable=fixme \
|
||||
--disable=cyclic-import \
|
||||
--disable=useless-import-alias \
|
||||
--disable=missing-function-docstring \
|
||||
--disable=missing-module-docstring \
|
||||
--disable=missing-class-docstring \
|
||||
--disable=too-many-function-args \
|
||||
--ignore=venv
|
||||
then
|
||||
echo 'Pylint passed ✅'
|
||||
else
|
||||
echo 'Pylint failed ❌'
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if python -m unittest tests/unittests.py
|
||||
then
|
||||
echo 'Unittests passed ✅'
|
||||
else
|
||||
echo 'Unittests failed ❌'
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo 'Well done.'
|
||||
@@ -0,0 +1,95 @@
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "shell_gpt"
|
||||
description = "A command-line productivity tool powered by OpenAI GPT models, will help you accomplish your tasks faster and more efficiently."
|
||||
keywords = ["shell", "gpt", "openai", "cli", "productivity", "cheet-sheet"]
|
||||
readme = "README.md"
|
||||
license = "MIT"
|
||||
requires-python = ">=3.6"
|
||||
authors = [{ name = "Farkhod Sadykov", email = "farkhod@sadykov.dev" }]
|
||||
dynamic = ["version"]
|
||||
classifiers = [
|
||||
"Operating System :: OS Independent",
|
||||
"Topic :: Software Development",
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Intended Audience :: Information Technology",
|
||||
"Intended Audience :: System Administrators",
|
||||
"Intended Audience :: Developers",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3 :: Only",
|
||||
"Programming Language :: Python :: 3.6",
|
||||
"Programming Language :: Python :: 3.7",
|
||||
"Programming Language :: Python :: 3.8",
|
||||
"Programming Language :: Python :: 3.9",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
]
|
||||
dependencies = [
|
||||
"requests >= 2.28.2, < 3.0.0",
|
||||
"typer >= 0.7.0, < 1.0.0",
|
||||
"click >= 7.1.1, < 9.0.0",
|
||||
"rich >= 10.11.0, < 13.0.0",
|
||||
"distro >= 1.8.0, < 2.0.0",
|
||||
'pyreadline3 >= 3.4.1, < 4.0.0; sys_platform == "win32"',
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
sgpt = "sgpt:cli"
|
||||
|
||||
[project.urls]
|
||||
homepage = "https://github.com/ther1d/shell_gpt"
|
||||
repository = "https://github.com/ther1d/shell_gpt"
|
||||
documentation = "https://github.com/TheR1D/shell_gpt/blob/main/README.md"
|
||||
|
||||
[project.optional-dependencies]
|
||||
test = [
|
||||
"pytest >= 7.2.2, < 8.0.0",
|
||||
"requests-mock[fixture] >= 1.10.0, < 2.0.0",
|
||||
"isort >= 5.12.0, < 6.0.0",
|
||||
"black == 23.1.0",
|
||||
"mypy == 1.1.1",
|
||||
"types-requests == 2.28.11.17",
|
||||
]
|
||||
dev = [
|
||||
"ruff == 0.0.256",
|
||||
"pre-commit >= 3.1.1, < 4.0.0",
|
||||
]
|
||||
|
||||
[tool.hatch.version]
|
||||
path = "sgpt/__init__.py"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
only-include = ["sgpt"]
|
||||
|
||||
[tool.hatch.build.targets.sdist]
|
||||
only-include = [
|
||||
"sgpt",
|
||||
"tests",
|
||||
"README.md",
|
||||
"LICENSE",
|
||||
"pyproject.toml",
|
||||
]
|
||||
|
||||
[tool.isort]
|
||||
profile = "black"
|
||||
skip = "__init__.py"
|
||||
|
||||
[tool.mypy]
|
||||
strict = true
|
||||
|
||||
[tool.ruff]
|
||||
select = [
|
||||
"E", # pycodestyle errors.
|
||||
"W", # pycodestyle warnings.
|
||||
"F", # pyflakes.
|
||||
"C", # flake8-comprehensions.
|
||||
"B", # flake8-bugbear.
|
||||
]
|
||||
ignore = [
|
||||
"E501", # line too long, handled by black.
|
||||
"C901", # too complex.
|
||||
"B008", # do not perform function calls in argument defaults.
|
||||
]
|
||||
@@ -1,6 +0,0 @@
|
||||
typer~=0.7.0
|
||||
requests~=2.28.2
|
||||
rich==13.3.1
|
||||
click~=8.1.3
|
||||
distro~=1.8.0
|
||||
setuptools==67.6.0
|
||||
@@ -0,0 +1,6 @@
|
||||
#!/bin/sh -e
|
||||
set -x
|
||||
|
||||
ruff sgpt tests scripts --fix
|
||||
black sgpt tests scripts
|
||||
isort sgpt tests scripts
|
||||
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -e
|
||||
set -x
|
||||
|
||||
mypy sgpt
|
||||
ruff sgpt tests scripts
|
||||
black sgpt tests --check
|
||||
isort sgpt tests scripts --check-only
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -e
|
||||
set -x
|
||||
|
||||
# shellcheck disable=SC2068
|
||||
pytest tests ${@}
|
||||
@@ -1,29 +0,0 @@
|
||||
from setuptools import setup, find_packages
|
||||
|
||||
# pylint: disable=consider-using-with
|
||||
setup(
|
||||
name="shell_gpt",
|
||||
version="0.8.8",
|
||||
packages=find_packages(),
|
||||
install_requires=[
|
||||
"typer~=0.7.0",
|
||||
"requests~=2.28.2",
|
||||
"rich==13.3.1",
|
||||
"distro~=1.8.0",
|
||||
],
|
||||
extras_require={
|
||||
':sys_platform == "win32"': ["pyreadline3"]
|
||||
},
|
||||
entry_points={
|
||||
"console_scripts": ["sgpt = sgpt:cli"],
|
||||
},
|
||||
author="Farkhod Sadykov",
|
||||
author_email="farkhod@sadykov.dev",
|
||||
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",
|
||||
)
|
||||
+4
-2
@@ -1,4 +1,4 @@
|
||||
from .config import config as config
|
||||
from .config import cfg as cfg
|
||||
from .cache import Cache as Cache
|
||||
from .client import OpenAIClient as OpenAIClient
|
||||
from .handlers.chat_handler import ChatHandler as ChatHandler
|
||||
@@ -6,5 +6,7 @@ from .handlers.default_handler import DefaultHandler as DefaultHandler
|
||||
from .handlers.repl_handler import ReplHandler as ReplHandler
|
||||
from . import utils as utils
|
||||
from .app import main as main
|
||||
from .app import entry_point as cli
|
||||
from .app import entry_point as cli # noqa: F401
|
||||
from . import make_prompt as make_prompt
|
||||
|
||||
__version__ = "0.8.9"
|
||||
|
||||
+12
-12
@@ -9,27 +9,27 @@ shell commands directly from the interface.
|
||||
|
||||
API Key is stored locally for easy use in future runs.
|
||||
"""
|
||||
import sys
|
||||
|
||||
# To allow users to use arrow keys in the REPL.
|
||||
import readline # pylint: disable=unused-import
|
||||
import readline # noqa: F401
|
||||
import sys
|
||||
|
||||
import typer
|
||||
|
||||
# Click is part of typer.
|
||||
from click import MissingParameter, BadArgumentUsage
|
||||
from sgpt import ChatHandler, DefaultHandler, ReplHandler, OpenAIClient, config
|
||||
from sgpt.utils import get_edited_prompt, run_command, ModelOptions
|
||||
from click import BadArgumentUsage, MissingParameter
|
||||
|
||||
from sgpt import ChatHandler, DefaultHandler, OpenAIClient, ReplHandler, cfg
|
||||
from sgpt.utils import ModelOptions, get_edited_prompt, run_command
|
||||
|
||||
|
||||
def main( # pylint: disable=too-many-arguments,too-many-locals
|
||||
def main(
|
||||
prompt: str = typer.Argument(
|
||||
None,
|
||||
show_default=False,
|
||||
help="The prompt to generate completions for.",
|
||||
),
|
||||
model: ModelOptions = typer.Option(
|
||||
ModelOptions(config.get("DEFAULT_MODEL")).value,
|
||||
ModelOptions(cfg.get("DEFAULT_MODEL")).value,
|
||||
help="OpenAI GPT model to use.",
|
||||
),
|
||||
temperature: float = typer.Option(
|
||||
@@ -74,13 +74,13 @@ def main( # pylint: disable=too-many-arguments,too-many-locals
|
||||
help="Start a REPL (Read–eval–print loop) session.",
|
||||
rich_help_panel="Chat Options",
|
||||
),
|
||||
show_chat: str = typer.Option( # pylint: disable=W0613
|
||||
show_chat: str = typer.Option(
|
||||
None,
|
||||
help="Show all messages from provided chat id.",
|
||||
callback=ChatHandler.show_messages_callback,
|
||||
rich_help_panel="Chat Options",
|
||||
),
|
||||
list_chat: bool = typer.Option( # pylint: disable=W0613
|
||||
list_chat: bool = typer.Option(
|
||||
False,
|
||||
help="List all existing chat ids.",
|
||||
callback=ChatHandler.list_ids,
|
||||
@@ -107,8 +107,8 @@ def main( # pylint: disable=too-many-arguments,too-many-locals
|
||||
if editor:
|
||||
prompt = get_edited_prompt()
|
||||
|
||||
api_host = config.get("OPENAI_API_HOST")
|
||||
api_key = config.get("OPENAI_API_KEY")
|
||||
api_host = cfg.get("OPENAI_API_HOST")
|
||||
api_key = cfg.get("OPENAI_API_KEY")
|
||||
client = OpenAIClient(api_host, api_key)
|
||||
|
||||
if repl:
|
||||
|
||||
+6
-5
@@ -1,10 +1,10 @@
|
||||
import json
|
||||
from hashlib import md5
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
from typing import Any, Callable, Generator, no_type_check
|
||||
|
||||
|
||||
class Cache: # pylint: disable=too-few-public-methods
|
||||
class Cache:
|
||||
"""
|
||||
Decorator class that adds caching functionality to a function.
|
||||
"""
|
||||
@@ -19,7 +19,7 @@ class Cache: # pylint: disable=too-few-public-methods
|
||||
self.cache_path = cache_path
|
||||
self.cache_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def __call__(self, func: Callable) -> Callable:
|
||||
def __call__(self, func: Callable[..., Any]) -> Callable[..., Any]:
|
||||
"""
|
||||
The Cache decorator.
|
||||
|
||||
@@ -27,7 +27,7 @@ class Cache: # pylint: disable=too-few-public-methods
|
||||
:return: Wrapped function with caching.
|
||||
"""
|
||||
|
||||
def wrapper(*args, **kwargs):
|
||||
def wrapper(*args: Any, **kwargs: Any) -> Generator[str, None, None]:
|
||||
# Exclude self instance from hashing.
|
||||
cache_key = md5(json.dumps((args[1:], kwargs)).encode("utf-8")).hexdigest()
|
||||
cache_file = self.cache_path / cache_key
|
||||
@@ -40,10 +40,11 @@ class Cache: # pylint: disable=too-few-public-methods
|
||||
result += i
|
||||
yield i
|
||||
cache_file.write_text(result)
|
||||
self._delete_oldest_files(self.length)
|
||||
self._delete_oldest_files(self.length) # type: ignore
|
||||
|
||||
return wrapper
|
||||
|
||||
@no_type_check
|
||||
def _delete_oldest_files(self, max_files: int) -> None:
|
||||
"""
|
||||
Class method to delete the oldest cached files in the CACHE_DIR folder.
|
||||
|
||||
+12
-14
@@ -1,16 +1,14 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import List, Dict, Mapping
|
||||
from typing import Dict, Generator, List
|
||||
|
||||
import requests
|
||||
|
||||
from sgpt import config, Cache
|
||||
from sgpt import Cache, cfg
|
||||
|
||||
|
||||
# pylint: skip-file
|
||||
CACHE_LENGTH = int(config.get("CACHE_LENGTH"))
|
||||
CACHE_PATH = Path(config.get("CACHE_PATH"))
|
||||
REQUEST_TIMEOUT = int(config.get("REQUEST_TIMEOUT"))
|
||||
CACHE_LENGTH = int(cfg.get("CACHE_LENGTH"))
|
||||
CACHE_PATH = Path(cfg.get("CACHE_PATH"))
|
||||
REQUEST_TIMEOUT = int(cfg.get("REQUEST_TIMEOUT"))
|
||||
|
||||
|
||||
class OpenAIClient:
|
||||
@@ -23,11 +21,11 @@ class OpenAIClient:
|
||||
@cache
|
||||
def _request(
|
||||
self,
|
||||
messages: List[Mapping[str, str]],
|
||||
messages: List[Dict[str, str]],
|
||||
model: str = "gpt-3.5-turbo",
|
||||
temperature: float = 1,
|
||||
top_probability: float = 1,
|
||||
) -> Dict:
|
||||
) -> Generator[str, None, None]:
|
||||
"""
|
||||
Make request to OpenAI ChatGPT API, read more:
|
||||
https://platform.openai.com/docs/api-reference/chat
|
||||
@@ -58,24 +56,24 @@ class OpenAIClient:
|
||||
# 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]":
|
||||
if data == "[DONE]": # type: ignore
|
||||
break
|
||||
if not data:
|
||||
continue
|
||||
data = json.loads(data)
|
||||
delta = data["choices"][0]["delta"]
|
||||
data = json.loads(data) # type: ignore
|
||||
delta = data["choices"][0]["delta"] # type: ignore
|
||||
if "content" not in delta:
|
||||
continue
|
||||
yield delta["content"]
|
||||
|
||||
def get_completion(
|
||||
self,
|
||||
messages: List[Mapping[str, str]],
|
||||
messages: List[Dict[str, str]],
|
||||
model: str = "gpt-3.5-turbo",
|
||||
temperature: float = 1,
|
||||
top_probability: float = 1,
|
||||
caching: bool = True,
|
||||
) -> str:
|
||||
) -> Generator[str, None, None]:
|
||||
"""
|
||||
Generates single completion for prompt (message).
|
||||
|
||||
|
||||
+7
-7
@@ -1,8 +1,8 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
from getpass import getpass
|
||||
from pathlib import Path
|
||||
from tempfile import gettempdir
|
||||
from typing import Any, Optional
|
||||
from typing import Any
|
||||
|
||||
from click import UsageError
|
||||
|
||||
@@ -30,7 +30,7 @@ DEFAULT_CONFIG = {
|
||||
}
|
||||
|
||||
|
||||
class Config(dict):
|
||||
class Config(dict): # type: ignore
|
||||
def __init__(self, config_path: Path, **defaults: Any):
|
||||
self.config_path = config_path
|
||||
|
||||
@@ -56,20 +56,20 @@ class Config(dict):
|
||||
def _exists(self) -> bool:
|
||||
return self.config_path.exists()
|
||||
|
||||
def _write(self):
|
||||
def _write(self) -> None:
|
||||
with open(self.config_path, "w", encoding="utf-8") as file:
|
||||
string_config = ""
|
||||
for key, value in self.items():
|
||||
string_config += f"{key}={value}\n"
|
||||
file.write(string_config)
|
||||
|
||||
def _read(self):
|
||||
def _read(self) -> None:
|
||||
with open(self.config_path, "r", encoding="utf-8") as file:
|
||||
for line in file:
|
||||
key, value = line.strip().split("=")
|
||||
self[key] = value
|
||||
|
||||
def get(self, key: str) -> Optional[str]:
|
||||
def get(self, key: str) -> str: # type: ignore
|
||||
# Prioritize environment variables over config file.
|
||||
value = os.getenv(key) or super().get(key)
|
||||
if not value:
|
||||
@@ -77,4 +77,4 @@ class Config(dict):
|
||||
return value
|
||||
|
||||
|
||||
config = Config(CONFIG_PATH, **DEFAULT_CONFIG)
|
||||
cfg = Config(CONFIG_PATH, **DEFAULT_CONFIG)
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import List, Dict, Optional, Callable, Generator
|
||||
from typing import Any, Callable, Dict, Generator, List, Optional
|
||||
|
||||
import typer
|
||||
from click import BadArgumentUsage
|
||||
|
||||
from sgpt import OpenAIClient, config, make_prompt
|
||||
from sgpt.utils import CompletionModes
|
||||
from sgpt import OpenAIClient, cfg, make_prompt
|
||||
from sgpt.handlers.handler import Handler
|
||||
from sgpt.utils import CompletionModes
|
||||
|
||||
CHAT_CACHE_LENGTH = int(config.get("CHAT_CACHE_LENGTH"))
|
||||
CHAT_CACHE_PATH = Path(config.get("CHAT_CACHE_PATH"))
|
||||
CHAT_CACHE_LENGTH = int(cfg.get("CHAT_CACHE_LENGTH"))
|
||||
CHAT_CACHE_PATH = Path(cfg.get("CHAT_CACHE_PATH"))
|
||||
|
||||
|
||||
class ChatSession:
|
||||
@@ -31,7 +31,7 @@ class ChatSession:
|
||||
self.storage_path = storage_path
|
||||
self.storage_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def __call__(self, func: Callable) -> Callable:
|
||||
def __call__(self, func: Callable[..., Any]) -> Callable[..., Any]:
|
||||
"""
|
||||
The Cache decorator.
|
||||
|
||||
@@ -39,7 +39,7 @@ class ChatSession:
|
||||
:return: Wrapped function with chat caching.
|
||||
"""
|
||||
|
||||
def wrapper(*args, **kwargs):
|
||||
def wrapper(*args: Any, **kwargs: Any) -> Generator[str, None, None]:
|
||||
chat_id = kwargs.pop("chat_id", None)
|
||||
messages = kwargs["messages"]
|
||||
if not chat_id:
|
||||
@@ -58,29 +58,29 @@ class ChatSession:
|
||||
|
||||
return wrapper
|
||||
|
||||
def _read(self, chat_id: str) -> List[Dict]:
|
||||
def _read(self, chat_id: str) -> List[Dict[str, str]]:
|
||||
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):
|
||||
def _write(self, messages: List[Dict[str, str]], chat_id: str) -> None:
|
||||
file_path = self.storage_path / chat_id
|
||||
json.dump(messages[-self.length :], file_path.open("w"))
|
||||
|
||||
def invalidate(self, chat_id: str):
|
||||
def invalidate(self, chat_id: str) -> None:
|
||||
file_path = self.storage_path / chat_id
|
||||
file_path.unlink(missing_ok=True)
|
||||
|
||||
def get_messages(self, chat_id):
|
||||
def get_messages(self, chat_id: str) -> List[str]:
|
||||
messages = self._read(chat_id)
|
||||
return [f"{message['role']}: {message['content']}" for message in messages]
|
||||
|
||||
def exists(self, chat_id: Optional[str]) -> bool:
|
||||
return chat_id and bool(self._read(chat_id))
|
||||
return bool(chat_id and bool(self._read(chat_id)))
|
||||
|
||||
def list(self):
|
||||
def list(self) -> List[Path]:
|
||||
# Get all files in the folder.
|
||||
files = self.storage_path.glob("*")
|
||||
# Sort files by last modification time in ascending order.
|
||||
@@ -90,7 +90,7 @@ class ChatSession:
|
||||
class ChatHandler(Handler):
|
||||
chat_session = ChatSession(CHAT_CACHE_LENGTH, CHAT_CACHE_PATH)
|
||||
|
||||
def __init__( # pylint: disable=too-many-arguments
|
||||
def __init__(
|
||||
self,
|
||||
client: OpenAIClient,
|
||||
chat_id: str,
|
||||
@@ -111,7 +111,7 @@ class ChatHandler(Handler):
|
||||
self.validate()
|
||||
|
||||
@classmethod
|
||||
def list_ids(cls, value) -> None:
|
||||
def list_ids(cls, value: str) -> None:
|
||||
if not value:
|
||||
return
|
||||
# Prints all existing chat IDs to the console.
|
||||
@@ -127,20 +127,20 @@ class ChatHandler(Handler):
|
||||
def is_shell_chat(self) -> bool:
|
||||
# TODO: Should be optimized for REPL mode.
|
||||
chat_history = self.chat_session.get_messages(self.chat_id)
|
||||
return chat_history and chat_history[0].endswith("###\nCommand:")
|
||||
return bool(chat_history and chat_history[0].endswith("###\nCommand:"))
|
||||
|
||||
@property
|
||||
def is_code_chat(self) -> bool:
|
||||
chat_history = self.chat_session.get_messages(self.chat_id)
|
||||
return chat_history and chat_history[0].endswith("###\nCode:")
|
||||
return bool(chat_history and chat_history[0].endswith("###\nCode:"))
|
||||
|
||||
@property
|
||||
def is_default_chat(self) -> bool:
|
||||
chat_history = self.chat_session.get_messages(self.chat_id)
|
||||
return chat_history and chat_history[0].endswith("###")
|
||||
return bool(chat_history and chat_history[0].endswith("###"))
|
||||
|
||||
@classmethod
|
||||
def show_messages_callback(cls, chat_id) -> None:
|
||||
def show_messages_callback(cls, chat_id: str) -> None:
|
||||
if not chat_id:
|
||||
return
|
||||
cls.show_messages(chat_id)
|
||||
@@ -193,8 +193,8 @@ class ChatHandler(Handler):
|
||||
)
|
||||
|
||||
@chat_session
|
||||
def get_completion( # pylint: disable=arguments-differ
|
||||
def get_completion(
|
||||
self,
|
||||
**kwargs,
|
||||
) -> Generator:
|
||||
**kwargs: Any,
|
||||
) -> Generator[str, None, None]:
|
||||
yield from super().get_completion(**kwargs)
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
from pathlib import Path
|
||||
|
||||
from sgpt import OpenAIClient, config, make_prompt
|
||||
from sgpt import OpenAIClient, cfg, make_prompt
|
||||
from sgpt.utils import CompletionModes
|
||||
|
||||
from .handler import Handler
|
||||
|
||||
CHAT_CACHE_LENGTH = int(config.get("CHAT_CACHE_LENGTH"))
|
||||
CHAT_CACHE_PATH = Path(config.get("CHAT_CACHE_PATH"))
|
||||
CHAT_CACHE_LENGTH = int(cfg.get("CHAT_CACHE_LENGTH"))
|
||||
CHAT_CACHE_PATH = Path(cfg.get("CHAT_CACHE_PATH"))
|
||||
|
||||
|
||||
class DefaultHandler(Handler):
|
||||
@@ -21,7 +22,7 @@ class DefaultHandler(Handler):
|
||||
self.mode = CompletionModes.get_mode(shell, code)
|
||||
self.model = model
|
||||
|
||||
def make_prompt(self, prompt) -> str:
|
||||
def make_prompt(self, prompt: str) -> str:
|
||||
prompt = prompt.strip()
|
||||
return make_prompt.initial(
|
||||
prompt,
|
||||
|
||||
@@ -1,27 +1,26 @@
|
||||
from typing import List, Dict, Generator
|
||||
from typing import Any, Dict, Generator, List
|
||||
|
||||
import typer
|
||||
|
||||
from sgpt import OpenAIClient
|
||||
from sgpt import config
|
||||
from sgpt import OpenAIClient, cfg
|
||||
|
||||
|
||||
class Handler:
|
||||
def __init__(self, client: OpenAIClient) -> None:
|
||||
self.client = client
|
||||
self.color = config.get("DEFAULT_COLOR")
|
||||
self.color = cfg.get("DEFAULT_COLOR")
|
||||
|
||||
def make_prompt(self, prompt) -> str:
|
||||
def make_prompt(self, prompt: str) -> str:
|
||||
raise NotImplementedError
|
||||
|
||||
def get_completion( # pylint: disable=too-many-arguments
|
||||
def get_completion(
|
||||
self,
|
||||
messages: List[Dict[str, str]],
|
||||
model: str = "gpt-3.5-turbo",
|
||||
temperature: float = 1,
|
||||
top_probability: float = 1,
|
||||
caching: bool = True,
|
||||
) -> Generator:
|
||||
) -> Generator[str, None, None]:
|
||||
yield from self.client.get_completion(
|
||||
messages,
|
||||
model,
|
||||
@@ -30,7 +29,7 @@ class Handler:
|
||||
caching=caching,
|
||||
)
|
||||
|
||||
def handle(self, prompt: str, **kwargs) -> str:
|
||||
def handle(self, prompt: str, **kwargs: Any) -> str:
|
||||
prompt = self.make_prompt(prompt)
|
||||
messages = [{"role": "user", "content": prompt}]
|
||||
full_completion = ""
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import typer
|
||||
from typing import Any
|
||||
|
||||
import typer
|
||||
from rich import print as rich_print
|
||||
from rich.rule import Rule
|
||||
|
||||
from sgpt.handlers.chat_handler import ChatHandler
|
||||
from sgpt.client import OpenAIClient
|
||||
from sgpt.handlers.chat_handler import ChatHandler
|
||||
from sgpt.utils import CompletionModes, run_command
|
||||
|
||||
|
||||
class ReplHandler(ChatHandler):
|
||||
def __init__( # pylint: disable=useless-parent-delegation,too-many-arguments
|
||||
def __init__(
|
||||
self,
|
||||
client: OpenAIClient,
|
||||
chat_id: str,
|
||||
@@ -19,7 +20,7 @@ class ReplHandler(ChatHandler):
|
||||
):
|
||||
super().__init__(client, chat_id, shell, code, model)
|
||||
|
||||
def handle(self, prompt: str, **kwargs) -> None:
|
||||
def handle(self, prompt: str, **kwargs: Any) -> None: # type: ignore
|
||||
if self.initiated:
|
||||
rich_print(Rule(title="Chat History", style="bold magenta"))
|
||||
self.show_messages(self.chat_id)
|
||||
|
||||
+1
-1
@@ -1,8 +1,8 @@
|
||||
import platform
|
||||
from os import getenv, pathsep
|
||||
from os.path import basename
|
||||
from distro import name as distro_name
|
||||
|
||||
from distro import name as distro_name
|
||||
|
||||
SHELL_PROMPT = """###
|
||||
Provide only {shell} commands for {os} without any description.
|
||||
|
||||
+2
-4
@@ -1,11 +1,9 @@
|
||||
import os
|
||||
import platform
|
||||
import shlex
|
||||
|
||||
from enum import Enum
|
||||
from tempfile import NamedTemporaryFile
|
||||
|
||||
import platform
|
||||
|
||||
from click import BadParameter
|
||||
|
||||
|
||||
@@ -21,7 +19,7 @@ class CompletionModes(Enum):
|
||||
CODE = "code"
|
||||
|
||||
@classmethod
|
||||
def get_mode(cls, shell, code) -> "CompletionModes":
|
||||
def get_mode(cls, shell: bool, code: bool) -> "CompletionModes":
|
||||
if shell:
|
||||
return CompletionModes.SHELL
|
||||
if code:
|
||||
|
||||
@@ -1,26 +1,25 @@
|
||||
"""
|
||||
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/.sgptrc
|
||||
Make sure you have your API key in place ~/.cfg/shell_gpt/.sgptrc
|
||||
or ENV variable OPENAI_API_KEY.
|
||||
It is useful for quick tests, saves a bit time.
|
||||
"""
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import os
|
||||
|
||||
from time import sleep
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from unittest import TestCase
|
||||
from unittest.mock import patch, ANY
|
||||
from tempfile import NamedTemporaryFile
|
||||
from time import sleep
|
||||
from unittest import TestCase
|
||||
from unittest.mock import ANY, patch
|
||||
from uuid import uuid4
|
||||
|
||||
import typer
|
||||
from typer.testing import CliRunner
|
||||
|
||||
from sgpt import main, config, OpenAIClient
|
||||
from sgpt import OpenAIClient, cfg, main
|
||||
from sgpt.handlers.handler import Handler
|
||||
|
||||
runner = CliRunner()
|
||||
@@ -86,7 +85,7 @@ class TestShellGpt(TestCase):
|
||||
try:
|
||||
compile(result.output, file.name, "exec")
|
||||
except SyntaxError:
|
||||
assert False, "The output is not valid Python code."
|
||||
assert False, "The output is not valid Python code." # noqa: B011
|
||||
file.seek(0)
|
||||
file.truncate()
|
||||
file.write(result.output)
|
||||
@@ -231,7 +230,7 @@ class TestShellGpt(TestCase):
|
||||
assert ">>> Sort by name" in result.stdout
|
||||
assert "ls" in result.stdout
|
||||
assert "ls | sort" in result.stdout
|
||||
chat_storage = config.get("CHAT_CACHE_PATH")
|
||||
chat_storage = cfg.get("CHAT_CACHE_PATH")
|
||||
tmp_chat = Path(chat_storage) / "temp"
|
||||
chat_messages = json.loads(tmp_chat.read_text())
|
||||
# TODO: Implement same check in chat mode tests.
|
||||
@@ -262,7 +261,7 @@ class TestShellGpt(TestCase):
|
||||
assert f">>> {inputs[1]}" in result.stdout
|
||||
assert "localhost:443" in result.stdout
|
||||
|
||||
chat_storage = config.get("CHAT_CACHE_PATH")
|
||||
chat_storage = cfg.get("CHAT_CACHE_PATH")
|
||||
tmp_chat = Path(chat_storage) / dict_arguments["--repl"]
|
||||
chat_messages = json.loads(tmp_chat.read_text())
|
||||
assert chat_messages[0]["content"].startswith("###")
|
||||
@@ -313,7 +312,7 @@ class TestShellGpt(TestCase):
|
||||
assert result.exit_code == 0
|
||||
|
||||
def test_color_output(self):
|
||||
color = config.get("DEFAULT_COLOR")
|
||||
color = cfg.get("DEFAULT_COLOR")
|
||||
handler = Handler(OpenAIClient("test", "test"))
|
||||
assert handler.color == color
|
||||
os.environ["DEFAULT_COLOR"] = "red"
|
||||
@@ -1,12 +1,13 @@
|
||||
import os
|
||||
import unittest
|
||||
import requests_mock
|
||||
|
||||
import requests
|
||||
import requests_mock
|
||||
|
||||
from sgpt import OpenAIClient
|
||||
|
||||
|
||||
class TestMain(unittest.TestCase): # pylint: disable=too-many-instance-attributes
|
||||
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.
|
||||
Reference in New Issue
Block a user