Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 21ca4378df | |||
| 48c77403a3 | |||
| e0f88630e6 | |||
| 88167486ab | |||
| 5bbc423840 | |||
| 9610525ecb | |||
| 0a5769f8a0 | |||
| 7cfc47cdc3 | |||
| 256b616f02 | |||
| 84a8876016 |
@@ -2,6 +2,28 @@
|
||||
|
||||

|
||||
|
||||
# Update Yolo v0.5 - Support for Claude and other providers
|
||||
|
||||
* Added Claude support. Can an API key from Anthropic, current model `claude-3-5-sonnet-20240620`.
|
||||
* ai_model.py to abstract model usage and allow adding new providers more easily
|
||||
* Rewrote some logic to simplify and generalize support for various new APIs (like Ollama, Claude)
|
||||
|
||||
# Update Yolo v0.4 - Support for Groq
|
||||
|
||||
* Added groq support. You can get an API key at `https://console.groq.com` and set mode to for instance support for Azure OpenAI. There is an `api` key in the `yolo.yaml` that can be set to `azure_openai` and then you can provide all the parameters accordingly in the yaml file as well (`api-version`, your `azure-endpoint`,...). The api key for azure is called `AZURE_OPENAI_API_KEY` by the way. It can be set via environment variable and config file.
|
||||
* It's now possible to change the color of the suggested command via config file
|
||||
* The "modify prompt" feature is now optional and can be toggled via config file.
|
||||
* Minor bug fixes (like copy to clipboard should work on macOS)
|
||||
|
||||
Tested on macOS and Linux. Windows hopefully still works also.`llama3-8b-8192`. groq is lightning fast.
|
||||
* Simplified and improved default `prompt.txt`,
|
||||
* Note: Testing shows that model `gpt-4o` gives the best results.
|
||||
|
||||
|
||||
# Update Yolo v0.3 - Support for Azure OpenAI
|
||||
|
||||
* Key changes are upgrades to the latest OpenAI libraries and
|
||||
|
||||
# Update Yolo v0.2 - Support for GPT-4 API
|
||||
|
||||
This update introduces the `yolo.yaml` configuration file. In this file you can specify which OpenAI model you want to query, and other settings. The safety switch also moved into this configuration file.
|
||||
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from openai import OpenAI
|
||||
from groq import Groq
|
||||
from ollama import Client
|
||||
from openai import AzureOpenAI
|
||||
from anthropic import Anthropic
|
||||
import os
|
||||
|
||||
|
||||
class AIModel(ABC):
|
||||
@abstractmethod
|
||||
def chat(self, model, messages):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def moderate(self, message):
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def get_model_client(config):
|
||||
api_provider = config["api"]
|
||||
|
||||
if api_provider == "" or api_provider == None:
|
||||
api_provider = "groq"
|
||||
|
||||
if api_provider == "groq":
|
||||
return GroqModel(api_key=os.environ.get("GROQ_API_KEY"))
|
||||
|
||||
elif api_provider == "openai":
|
||||
api_key = os.getenv("OPENAI_API_KEY")
|
||||
if not api_key:
|
||||
api_key = config["openai_api_key"]
|
||||
if not api_key: # If statement to avoid "invalid filepath" error
|
||||
home_path = os.path.expanduser("~")
|
||||
api_key = (
|
||||
open(os.path.join(home_path, ".openai.apikey"), "r")
|
||||
.readline()
|
||||
.strip()
|
||||
)
|
||||
api_key = api_key
|
||||
|
||||
return OpenAIModel(api_key=api_key)
|
||||
|
||||
elif api_provider == "azure":
|
||||
api_key = os.getenv("AZURE_OPENAI_API_KEY")
|
||||
if not api_key:
|
||||
api_key = config["azure_openai_api_key"]
|
||||
if not api_key:
|
||||
home_path = os.path.expanduser("~")
|
||||
api_key = (
|
||||
open(os.path.join(home_path, ".azureopenai.apikey"), "r")
|
||||
.readline()
|
||||
.strip()
|
||||
)
|
||||
|
||||
return AzureOpenAIModel(
|
||||
api_key=api_key,
|
||||
azure_endpoint=config["azure_endpoint"],
|
||||
api_version=config["azure_api_version"],
|
||||
)
|
||||
|
||||
elif api_provider == "ollama":
|
||||
ollama_api = os.environ.get("OLLAMA_ENDPOINT", "http://localhost:11434")
|
||||
# ollama_model = os.environ.get("OLLAMA_MODEL", "llama3-8b-8192")
|
||||
return OllamaModel(ollama_api)
|
||||
|
||||
if api_provider == "anthropic":
|
||||
api_key = os.getenv("ANTHROPIC_API_KEY")
|
||||
if not api_key:
|
||||
api_key = config["anthropic_api_key"]
|
||||
return AnthropicModel(api_key=api_key)
|
||||
else:
|
||||
raise ValueError(f"Invalid AI model provider: {api_provider}")
|
||||
|
||||
|
||||
class GroqModel(AIModel):
|
||||
def __init__(self, api_key):
|
||||
self.client = Groq(api_key=api_key)
|
||||
|
||||
def chat(self, messages, model, temperature, max_tokens):
|
||||
resp = self.client.chat.completions.create(
|
||||
model=model,
|
||||
messages=messages,
|
||||
temperature=temperature,
|
||||
max_tokens=max_tokens,
|
||||
)
|
||||
return resp.choices[0].message.content
|
||||
|
||||
def moderate(self, message):
|
||||
pass
|
||||
|
||||
|
||||
class OpenAIModel(AIModel):
|
||||
def __init__(self, api_key):
|
||||
self.client = OpenAI(api_key=api_key)
|
||||
|
||||
def chat(self, messages, model, temperature, max_tokens):
|
||||
resp = self.client.chat.completions.create(
|
||||
model=model,
|
||||
messages=messages,
|
||||
temperature=temperature,
|
||||
max_tokens=max_tokens,
|
||||
)
|
||||
|
||||
return resp.choices[0].message.content
|
||||
|
||||
def moderate(self, message):
|
||||
return self.client.moderations.create(input=message)
|
||||
|
||||
|
||||
class OllamaModel(AIModel):
|
||||
def __init__(self, host):
|
||||
self.client = Client(host=host)
|
||||
|
||||
def chat(self, messages, model, temperature, max_tokens):
|
||||
resp = self.client.chat(model=model, messages=messages)
|
||||
return resp["message"]["content"]
|
||||
|
||||
def moderate(self, message):
|
||||
pass
|
||||
|
||||
|
||||
class AzureOpenAIModel(AIModel):
|
||||
def __init__(self, azure_endpoint, api_key, api_version):
|
||||
self.client = AzureOpenAI(
|
||||
azure_endpoint=azure_endpoint, api_key=api_key, api_version=api_version
|
||||
)
|
||||
|
||||
def chat(self, messages, model, temperature, max_tokens):
|
||||
|
||||
resp = self.client.chat.completions.create(
|
||||
model=model,
|
||||
messages=messages,
|
||||
temperature=temperature,
|
||||
max_tokens=max_tokens,
|
||||
)
|
||||
|
||||
return resp.choices[0].message.content
|
||||
|
||||
def moderate(self, message):
|
||||
return self.client.moderations.create(input=message)
|
||||
|
||||
|
||||
class AnthropicModel(AIModel):
|
||||
def __init__(self, api_key):
|
||||
self.client = Anthropic(api_key=api_key)
|
||||
|
||||
def chat(self, messages, model, temperature, max_tokens):
|
||||
## Anthropic requires the system prompt to be passed separately
|
||||
## Hence extracting system prompt role from the messages
|
||||
## and then passing the messages without the system role
|
||||
## messages is not subscriptable, so we need to convert it to a list
|
||||
system_prompt = next(
|
||||
(m.get("content", "") for m in messages if m.get("role") == "system"), ""
|
||||
)
|
||||
|
||||
# Remove system messages from the list
|
||||
user_messages = [m for m in messages if m.get("role") != "system"]
|
||||
resp = self.client.messages.create(
|
||||
model=model,
|
||||
system=system_prompt,
|
||||
messages=user_messages,
|
||||
temperature=temperature,
|
||||
max_tokens=max_tokens,
|
||||
)
|
||||
|
||||
return resp.content[0].text
|
||||
|
||||
def moderate(self, message):
|
||||
pass
|
||||
@@ -1,27 +1,78 @@
|
||||
[MASTER]
|
||||
[MAIN]
|
||||
|
||||
# Analyse import fallback blocks. This can be used to support both Python 2 and
|
||||
# 3 compatible code, which means that the block might have code that exists
|
||||
# only in one or another interpreter, leading to false positives when analysed.
|
||||
analyse-fallback-blocks=no
|
||||
|
||||
# Clear in-memory caches upon conclusion of linting. Useful if running pylint
|
||||
# in a server-like mode.
|
||||
clear-cache-post-run=no
|
||||
|
||||
# Load and enable all available extensions. Use --list-extensions to see a list
|
||||
# all available extensions.
|
||||
#enable-all-extensions=
|
||||
|
||||
# In error mode, messages with a category besides ERROR or FATAL are
|
||||
# suppressed, and no reports are done by default. Error mode is compatible with
|
||||
# disabling specific errors.
|
||||
#errors-only=
|
||||
|
||||
# Always return a 0 (non-error) status code, even if lint errors are found.
|
||||
# This is primarily useful in continuous integration scripts.
|
||||
#exit-zero=
|
||||
|
||||
# A comma-separated list of package or module names from where C extensions may
|
||||
# be loaded. Extensions are loading into the active Python interpreter and may
|
||||
# run arbitrary code.
|
||||
extension-pkg-allow-list=
|
||||
|
||||
# A comma-separated list of package or module names from where C extensions may
|
||||
# be loaded. Extensions are loading into the active Python interpreter and may
|
||||
# run arbitrary code. (This is an alternative name to extension-pkg-allow-list
|
||||
# for backward compatibility.)
|
||||
extension-pkg-whitelist=
|
||||
|
||||
# Specify a score threshold to be exceeded before program exits with error.
|
||||
fail-under=10.0
|
||||
# Return non-zero exit code if any of these messages/categories are detected,
|
||||
# even if score is above --fail-under value. Syntax same as enable. Messages
|
||||
# specified are enabled, while categories only check already-enabled messages.
|
||||
fail-on=
|
||||
|
||||
# Add files or directories to the blacklist. They should be base names, not
|
||||
# paths.
|
||||
# Specify a score threshold under which the program will exit with error.
|
||||
fail-under=10
|
||||
|
||||
# Interpret the stdin as a python script, whose filename needs to be passed as
|
||||
# the module_or_package argument.
|
||||
#from-stdin=
|
||||
|
||||
# Files or directories to be skipped. They should be base names, not paths.
|
||||
ignore=CVS
|
||||
|
||||
# Add files or directories matching the regex patterns to the blacklist. The
|
||||
# regex matches against base names, not paths.
|
||||
ignore-patterns=
|
||||
# Add files or directories matching the regular expressions patterns to the
|
||||
# ignore-list. The regex matches against paths and can be in Posix or Windows
|
||||
# format. Because '\\' represents the directory delimiter on Windows systems,
|
||||
# it can't be used as an escape character.
|
||||
ignore-paths=
|
||||
|
||||
# Files or directories matching the regular expression patterns are skipped.
|
||||
# The regex matches against base names, not paths. The default value ignores
|
||||
# Emacs file locks
|
||||
ignore-patterns=^\.#
|
||||
|
||||
# List of module names for which member attributes should not be checked and
|
||||
# will not be imported (useful for modules/projects where namespaces are
|
||||
# manipulated during runtime and thus existing member attributes cannot be
|
||||
# deduced by static analysis). It supports qualified module names, as well as
|
||||
# Unix pattern matching.
|
||||
ignored-modules=
|
||||
|
||||
# Python code to execute, usually for sys.path manipulation such as
|
||||
# pygtk.require().
|
||||
#init-hook=
|
||||
|
||||
# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
|
||||
# number of processors available to use.
|
||||
# number of processors available to use, and will cap the count on Windows to
|
||||
# avoid hangs.
|
||||
jobs=1
|
||||
|
||||
# Control the amount of potential inferred values when inferring a single
|
||||
@@ -36,6 +87,23 @@ load-plugins=
|
||||
# Pickle collected data for later comparisons.
|
||||
persistent=yes
|
||||
|
||||
# Resolve imports to .pyi stubs if available. May reduce no-member messages and
|
||||
# increase not-an-iterable messages.
|
||||
prefer-stubs=no
|
||||
|
||||
# Minimum Python version to use for version dependent checks. Will default to
|
||||
# the version used to run pylint.
|
||||
py-version=3.10
|
||||
|
||||
# Discover python modules and packages in the file system subtree.
|
||||
recursive=no
|
||||
|
||||
# Add paths to the list of the source roots. Supports globbing patterns. The
|
||||
# source root is an absolute path or a path relative to the current working
|
||||
# directory used to determine a package namespace for modules located under the
|
||||
# source root.
|
||||
source-roots=
|
||||
|
||||
# When enabled, pylint would attempt to guess common misconfiguration and emit
|
||||
# user-friendly hints instead of false-positive error messages.
|
||||
suggestion-mode=yes
|
||||
@@ -44,227 +112,8 @@ suggestion-mode=yes
|
||||
# active Python interpreter and may run arbitrary code.
|
||||
unsafe-load-any-extension=no
|
||||
|
||||
|
||||
[MESSAGES CONTROL]
|
||||
|
||||
# Only show warnings with the listed confidence levels. Leave empty to show
|
||||
# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED.
|
||||
confidence=
|
||||
|
||||
# Enable the message, report, category or checker with the given id(s). You can
|
||||
# either give multiple identifier separated by comma (,) or put this option
|
||||
# multiple time (only on the command line, not in the configuration file where
|
||||
# it should appear only once). See also the "--disable" option for examples.
|
||||
enable=c-extension-no-member
|
||||
|
||||
|
||||
[REPORTS]
|
||||
|
||||
# Python expression which should return a score less than or equal to 10. You
|
||||
# have access to the variables 'error', 'warning', 'refactor', and 'convention'
|
||||
# which contain the number of messages in each category, as well as 'statement'
|
||||
# which is the total number of statements analyzed. This score is used by the
|
||||
# global evaluation report (RP0004).
|
||||
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
|
||||
|
||||
# Template used to display messages. This is a python new-style format string
|
||||
# used to format the message information. See doc for all details.
|
||||
#msg-template=
|
||||
|
||||
# Set the output format. Available formats are text, parseable, colorized, json
|
||||
# and msvs (visual studio). You can also give a reporter class, e.g.
|
||||
# mypackage.mymodule.MyReporterClass.
|
||||
output-format=text
|
||||
|
||||
# Tells whether to display a full report or only the messages.
|
||||
reports=no
|
||||
|
||||
# Activate the evaluation score.
|
||||
score=yes
|
||||
|
||||
|
||||
[REFACTORING]
|
||||
|
||||
# Maximum number of nested blocks for function / method body
|
||||
max-nested-blocks=5
|
||||
|
||||
# Complete name of functions that never returns. When checking for
|
||||
# inconsistent-return-statements if a never returning function is called then
|
||||
# it will be considered as an explicit return statement and no message will be
|
||||
# printed.
|
||||
never-returning-functions=sys.exit
|
||||
|
||||
|
||||
[LOGGING]
|
||||
|
||||
# The type of string formatting that logging methods do. `old` means using %
|
||||
# formatting, `new` is for `{}` formatting.
|
||||
logging-format-style=old
|
||||
|
||||
# Logging modules to check that the string format arguments are in logging
|
||||
# function parameter format.
|
||||
logging-modules=logging
|
||||
|
||||
|
||||
[SPELLING]
|
||||
|
||||
# Limits count of emitted suggestions for spelling mistakes.
|
||||
max-spelling-suggestions=4
|
||||
|
||||
# Spelling dictionary name. Available dictionaries: none. To make it work,
|
||||
# install the python-enchant package.
|
||||
spelling-dict=
|
||||
|
||||
# List of comma separated words that should not be checked.
|
||||
spelling-ignore-words=
|
||||
|
||||
# A path to a file that contains the private dictionary; one word per line.
|
||||
spelling-private-dict-file=
|
||||
|
||||
# Tells whether to store unknown words to the private dictionary (see the
|
||||
# --spelling-private-dict-file option) instead of raising a message.
|
||||
spelling-store-unknown-words=no
|
||||
|
||||
|
||||
[MISCELLANEOUS]
|
||||
|
||||
# List of note tags to take in consideration, separated by a comma.
|
||||
notes=FIXME,
|
||||
XXX,
|
||||
TODO
|
||||
|
||||
# Regular expression of note tags to take in consideration.
|
||||
#notes-rgx=
|
||||
|
||||
|
||||
[TYPECHECK]
|
||||
|
||||
# List of decorators that produce context managers, such as
|
||||
# contextlib.contextmanager. Add to this list to register other decorators that
|
||||
# produce valid context managers.
|
||||
contextmanager-decorators=contextlib.contextmanager
|
||||
|
||||
# List of members which are set dynamically and missed by pylint inference
|
||||
# system, and so shouldn't trigger E1101 when accessed. Python regular
|
||||
# expressions are accepted.
|
||||
generated-members=
|
||||
|
||||
# Tells whether missing members accessed in mixin class should be ignored. A
|
||||
# mixin class is detected if its name ends with "mixin" (case insensitive).
|
||||
ignore-mixin-members=yes
|
||||
|
||||
# Tells whether to warn about missing members when the owner of the attribute
|
||||
# is inferred to be None.
|
||||
ignore-none=yes
|
||||
|
||||
# This flag controls whether pylint should warn about no-member and similar
|
||||
# checks whenever an opaque object is returned when inferring. The inference
|
||||
# can return multiple potential results while evaluating a Python object, but
|
||||
# some branches might not be evaluated, which results in partial inference. In
|
||||
# that case, it might be useful to still emit no-member and other checks for
|
||||
# the rest of the inferred objects.
|
||||
ignore-on-opaque-inference=yes
|
||||
|
||||
# List of class names for which member attributes should not be checked (useful
|
||||
# for classes with dynamically set attributes). This supports the use of
|
||||
# qualified names.
|
||||
ignored-classes=optparse.Values,thread._local,_thread._local
|
||||
|
||||
# List of module names for which member attributes should not be checked
|
||||
# (useful for modules/projects where namespaces are manipulated during runtime
|
||||
# and thus existing member attributes cannot be deduced by static analysis). It
|
||||
# supports qualified module names, as well as Unix pattern matching.
|
||||
ignored-modules=
|
||||
|
||||
# Show a hint with possible names when a member name was not found. The aspect
|
||||
# of finding the hint is based on edit distance.
|
||||
missing-member-hint=yes
|
||||
|
||||
# The minimum edit distance a name should have in order to be considered a
|
||||
# similar match for a missing member name.
|
||||
missing-member-hint-distance=1
|
||||
|
||||
# The total number of similar names that should be taken in consideration when
|
||||
# showing a hint for a missing member.
|
||||
missing-member-max-choices=1
|
||||
|
||||
# List of decorators that change the signature of a decorated function.
|
||||
signature-mutators=
|
||||
|
||||
|
||||
[VARIABLES]
|
||||
|
||||
# List of additional names supposed to be defined in builtins. Remember that
|
||||
# you should avoid defining new builtins when possible.
|
||||
additional-builtins=
|
||||
|
||||
# Tells whether unused global variables should be treated as a violation.
|
||||
allow-global-unused-variables=yes
|
||||
|
||||
# List of strings which can identify a callback function by name. A callback
|
||||
# name must start or end with one of those strings.
|
||||
callbacks=cb_,
|
||||
_cb
|
||||
|
||||
# A regular expression matching the name of dummy variables (i.e. expected to
|
||||
# not be used).
|
||||
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
|
||||
|
||||
# Argument names that match this expression will be ignored. Default to name
|
||||
# with leading underscore.
|
||||
ignored-argument-names=_.*|^ignored_|^unused_
|
||||
|
||||
# Tells whether we should check for unused import in __init__ files.
|
||||
init-import=no
|
||||
|
||||
# List of qualified module names which can have objects that can redefine
|
||||
# builtins.
|
||||
redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
|
||||
|
||||
|
||||
[FORMAT]
|
||||
|
||||
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
|
||||
expected-line-ending-format=
|
||||
|
||||
# Regexp for a line that is allowed to be longer than the limit.
|
||||
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
|
||||
|
||||
# Number of spaces of indent required inside a hanging or continued line.
|
||||
indent-after-paren=4
|
||||
|
||||
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
|
||||
# tab).
|
||||
indent-string=' '
|
||||
|
||||
# Maximum number of characters on a single line.
|
||||
max-line-length=100
|
||||
|
||||
# Maximum number of lines in a module.
|
||||
max-module-lines=1000
|
||||
|
||||
# Allow the body of a class to be on the same line as the declaration if body
|
||||
# contains single statement.
|
||||
single-line-class-stmt=no
|
||||
|
||||
# Allow the body of an if to be on the same line as the test if there is no
|
||||
# else.
|
||||
single-line-if-stmt=no
|
||||
|
||||
|
||||
[SIMILARITIES]
|
||||
|
||||
# Ignore comments when computing similarities.
|
||||
ignore-comments=yes
|
||||
|
||||
# Ignore docstrings when computing similarities.
|
||||
ignore-docstrings=yes
|
||||
|
||||
# Ignore imports when computing similarities.
|
||||
ignore-imports=no
|
||||
|
||||
# Minimum lines number of a similarity.
|
||||
min-similarity-lines=4
|
||||
# In verbose mode, extra non-checker-related info will be displayed.
|
||||
#verbose=
|
||||
|
||||
|
||||
[BASIC]
|
||||
@@ -273,13 +122,15 @@ min-similarity-lines=4
|
||||
argument-naming-style=snake_case
|
||||
|
||||
# Regular expression matching correct argument names. Overrides argument-
|
||||
# naming-style.
|
||||
# naming-style. If left empty, argument names will be checked with the set
|
||||
# naming style.
|
||||
#argument-rgx=
|
||||
|
||||
# Naming style matching correct attribute names.
|
||||
attr-naming-style=snake_case
|
||||
|
||||
# Regular expression matching correct attribute names. Overrides attr-naming-
|
||||
# style. If left empty, attribute names will be checked with the set naming
|
||||
# style.
|
||||
#attr-rgx=
|
||||
|
||||
@@ -299,20 +150,30 @@ bad-names-rgxs=
|
||||
class-attribute-naming-style=any
|
||||
|
||||
# Regular expression matching correct class attribute names. Overrides class-
|
||||
# attribute-naming-style.
|
||||
# attribute-naming-style. If left empty, class attribute names will be checked
|
||||
# with the set naming style.
|
||||
#class-attribute-rgx=
|
||||
|
||||
# Naming style matching correct class constant names.
|
||||
class-const-naming-style=UPPER_CASE
|
||||
|
||||
# Regular expression matching correct class constant names. Overrides class-
|
||||
# const-naming-style. If left empty, class constant names will be checked with
|
||||
# the set naming style.
|
||||
#class-const-rgx=
|
||||
|
||||
# Naming style matching correct class names.
|
||||
class-naming-style=PascalCase
|
||||
|
||||
# Regular expression matching correct class names. Overrides class-naming-
|
||||
# style.
|
||||
# style. If left empty, class names will be checked with the set naming style.
|
||||
#class-rgx=
|
||||
|
||||
# Naming style matching correct constant names.
|
||||
const-naming-style=UPPER_CASE
|
||||
|
||||
# Regular expression matching correct constant names. Overrides const-naming-
|
||||
# style. If left empty, constant names will be checked with the set naming
|
||||
# style.
|
||||
#const-rgx=
|
||||
|
||||
@@ -324,7 +185,8 @@ docstring-min-length=-1
|
||||
function-naming-style=snake_case
|
||||
|
||||
# Regular expression matching correct function names. Overrides function-
|
||||
# naming-style.
|
||||
# naming-style. If left empty, function names will be checked with the set
|
||||
# naming style.
|
||||
#function-rgx=
|
||||
|
||||
# Good variable names which should always be accepted, separated by a comma.
|
||||
@@ -346,21 +208,22 @@ include-naming-hint=no
|
||||
inlinevar-naming-style=any
|
||||
|
||||
# Regular expression matching correct inline iteration names. Overrides
|
||||
# inlinevar-naming-style.
|
||||
# inlinevar-naming-style. If left empty, inline iteration names will be checked
|
||||
# with the set naming style.
|
||||
#inlinevar-rgx=
|
||||
|
||||
# Naming style matching correct method names.
|
||||
method-naming-style=snake_case
|
||||
|
||||
# Regular expression matching correct method names. Overrides method-naming-
|
||||
# style.
|
||||
# style. If left empty, method names will be checked with the set naming style.
|
||||
#method-rgx=
|
||||
|
||||
# Naming style matching correct module names.
|
||||
module-naming-style=snake_case
|
||||
|
||||
# Regular expression matching correct module names. Overrides module-naming-
|
||||
# style.
|
||||
# style. If left empty, module names will be checked with the set naming style.
|
||||
#module-rgx=
|
||||
|
||||
# Colon-delimited sets of names that determine each other's naming style when
|
||||
@@ -376,90 +239,56 @@ no-docstring-rgx=^_
|
||||
# These decorators are taken in consideration only for invalid-name.
|
||||
property-classes=abc.abstractproperty
|
||||
|
||||
# Regular expression matching correct type alias names. If left empty, type
|
||||
# alias names will be checked with the set naming style.
|
||||
#typealias-rgx=
|
||||
|
||||
# Regular expression matching correct type variable names. If left empty, type
|
||||
# variable names will be checked with the set naming style.
|
||||
#typevar-rgx=
|
||||
|
||||
# Naming style matching correct variable names.
|
||||
variable-naming-style=snake_case
|
||||
|
||||
# Regular expression matching correct variable names. Overrides variable-
|
||||
# naming-style.
|
||||
# naming-style. If left empty, variable names will be checked with the set
|
||||
# naming style.
|
||||
#variable-rgx=
|
||||
|
||||
|
||||
[STRING]
|
||||
|
||||
# This flag controls whether inconsistent-quotes generates a warning when the
|
||||
# character used as a quote delimiter is used inconsistently within a module.
|
||||
check-quote-consistency=no
|
||||
|
||||
# This flag controls whether the implicit-str-concat should generate a warning
|
||||
# on implicit string concatenation in sequences defined over several lines.
|
||||
check-str-concat-over-line-jumps=no
|
||||
|
||||
|
||||
[IMPORTS]
|
||||
|
||||
# List of modules that can be imported at any level, not just the top level
|
||||
# one.
|
||||
allow-any-import-level=
|
||||
|
||||
# Allow wildcard imports from modules that define __all__.
|
||||
allow-wildcard-with-all=no
|
||||
|
||||
# Analyse import fallback blocks. This can be used to support both Python 2 and
|
||||
# 3 compatible code, which means that the block might have code that exists
|
||||
# only in one or another interpreter, leading to false positives when analysed.
|
||||
analyse-fallback-blocks=no
|
||||
|
||||
# Deprecated modules which should not be used, separated by a comma.
|
||||
deprecated-modules=optparse,tkinter.tix
|
||||
|
||||
# Create a graph of external dependencies in the given file (report RP0402 must
|
||||
# not be disabled).
|
||||
ext-import-graph=
|
||||
|
||||
# Create a graph of every (i.e. internal and external) dependencies in the
|
||||
# given file (report RP0402 must not be disabled).
|
||||
import-graph=
|
||||
|
||||
# Create a graph of internal dependencies in the given file (report RP0402 must
|
||||
# not be disabled).
|
||||
int-import-graph=
|
||||
|
||||
# Force import order to recognize a module as part of the standard
|
||||
# compatibility libraries.
|
||||
known-standard-library=
|
||||
|
||||
# Force import order to recognize a module as part of a third party library.
|
||||
known-third-party=enchant
|
||||
|
||||
# Couples of modules and preferred modules, separated by a comma.
|
||||
preferred-modules=
|
||||
|
||||
|
||||
[CLASSES]
|
||||
|
||||
# Warn about protected attribute access inside special methods
|
||||
check-protected-access-in-special-methods=no
|
||||
|
||||
# List of method names used to declare (i.e. assign) instance attributes.
|
||||
defining-attr-methods=__init__,
|
||||
__new__,
|
||||
setUp,
|
||||
asyncSetUp,
|
||||
__post_init__
|
||||
|
||||
# List of member names, which should be excluded from the protected access
|
||||
# warning.
|
||||
exclude-protected=_asdict,
|
||||
_fields,
|
||||
_replace,
|
||||
_source,
|
||||
_make
|
||||
exclude-protected=_asdict,_fields,_replace,_source,_make,os._exit
|
||||
|
||||
# List of valid names for the first argument in a class method.
|
||||
valid-classmethod-first-arg=cls
|
||||
|
||||
# List of valid names for the first argument in a metaclass class method.
|
||||
valid-metaclass-classmethod-first-arg=cls
|
||||
valid-metaclass-classmethod-first-arg=mcs
|
||||
|
||||
|
||||
[DESIGN]
|
||||
|
||||
# List of regular expressions of class ancestor names to ignore when counting
|
||||
# public methods (see R0903)
|
||||
exclude-too-few-public-methods=
|
||||
|
||||
# List of qualified class names to ignore when counting class parents (see
|
||||
# R0901)
|
||||
ignored-parents=
|
||||
|
||||
# Maximum number of arguments for function / method.
|
||||
max-args=5
|
||||
|
||||
@@ -493,7 +322,323 @@ min-public-methods=2
|
||||
|
||||
[EXCEPTIONS]
|
||||
|
||||
# Exceptions that will emit a warning when being caught. Defaults to
|
||||
# "BaseException, Exception".
|
||||
overgeneral-exceptions=BaseException,
|
||||
Exception
|
||||
# Exceptions that will emit a warning when caught.
|
||||
overgeneral-exceptions=builtins.BaseException,builtins.Exception
|
||||
|
||||
|
||||
[FORMAT]
|
||||
|
||||
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
|
||||
expected-line-ending-format=
|
||||
|
||||
# Regexp for a line that is allowed to be longer than the limit.
|
||||
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
|
||||
|
||||
# Number of spaces of indent required inside a hanging or continued line.
|
||||
indent-after-paren=4
|
||||
|
||||
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
|
||||
# tab).
|
||||
indent-string=' '
|
||||
|
||||
# Maximum number of characters on a single line.
|
||||
max-line-length=100
|
||||
|
||||
# Maximum number of lines in a module.
|
||||
max-module-lines=1000
|
||||
|
||||
# Allow the body of a class to be on the same line as the declaration if body
|
||||
# contains single statement.
|
||||
single-line-class-stmt=no
|
||||
|
||||
# Allow the body of an if to be on the same line as the test if there is no
|
||||
# else.
|
||||
single-line-if-stmt=no
|
||||
|
||||
|
||||
[IMPORTS]
|
||||
|
||||
# List of modules that can be imported at any level, not just the top level
|
||||
# one.
|
||||
allow-any-import-level=
|
||||
|
||||
# Allow explicit reexports by alias from a package __init__.
|
||||
allow-reexport-from-package=no
|
||||
|
||||
# Allow wildcard imports from modules that define __all__.
|
||||
allow-wildcard-with-all=no
|
||||
|
||||
# Deprecated modules which should not be used, separated by a comma.
|
||||
deprecated-modules=
|
||||
|
||||
# Output a graph (.gv or any supported image format) of external dependencies
|
||||
# to the given file (report RP0402 must not be disabled).
|
||||
ext-import-graph=
|
||||
|
||||
# Output a graph (.gv or any supported image format) of all (i.e. internal and
|
||||
# external) dependencies to the given file (report RP0402 must not be
|
||||
# disabled).
|
||||
import-graph=
|
||||
|
||||
# Output a graph (.gv or any supported image format) of internal dependencies
|
||||
# to the given file (report RP0402 must not be disabled).
|
||||
int-import-graph=
|
||||
|
||||
# Force import order to recognize a module as part of the standard
|
||||
# compatibility libraries.
|
||||
known-standard-library=
|
||||
|
||||
# Force import order to recognize a module as part of a third party library.
|
||||
known-third-party=enchant
|
||||
|
||||
# Couples of modules and preferred modules, separated by a comma.
|
||||
preferred-modules=
|
||||
|
||||
|
||||
[LOGGING]
|
||||
|
||||
# The type of string formatting that logging methods do. `old` means using %
|
||||
# formatting, `new` is for `{}` formatting.
|
||||
logging-format-style=old
|
||||
|
||||
# Logging modules to check that the string format arguments are in logging
|
||||
# function parameter format.
|
||||
logging-modules=logging
|
||||
|
||||
|
||||
[MESSAGES CONTROL]
|
||||
|
||||
# Only show warnings with the listed confidence levels. Leave empty to show
|
||||
# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE,
|
||||
# UNDEFINED.
|
||||
confidence=HIGH,
|
||||
CONTROL_FLOW,
|
||||
INFERENCE,
|
||||
INFERENCE_FAILURE,
|
||||
UNDEFINED
|
||||
|
||||
# Disable the message, report, category or checker with the given id(s). You
|
||||
# can either give multiple identifiers separated by comma (,) or put this
|
||||
# option multiple times (only on the command line, not in the configuration
|
||||
# file where it should appear only once). You can also use "--disable=all" to
|
||||
# disable everything first and then re-enable specific checks. For example, if
|
||||
# you want to run only the similarities checker, you can use "--disable=all
|
||||
# --enable=similarities". If you want to run only the classes checker, but have
|
||||
# no Warning level messages displayed, use "--disable=all --enable=classes
|
||||
# --disable=W".
|
||||
disable=raw-checker-failed,
|
||||
bad-inline-option,
|
||||
locally-disabled,
|
||||
file-ignored,
|
||||
suppressed-message,
|
||||
useless-suppression,
|
||||
deprecated-pragma,
|
||||
use-symbolic-message-instead,
|
||||
use-implicit-booleaness-not-comparison-to-string,
|
||||
use-implicit-booleaness-not-comparison-to-zero
|
||||
|
||||
# Enable the message, report, category or checker with the given id(s). You can
|
||||
# either give multiple identifier separated by comma (,) or put this option
|
||||
# multiple time (only on the command line, not in the configuration file where
|
||||
# it should appear only once). See also the "--disable" option for examples.
|
||||
enable=
|
||||
|
||||
|
||||
[METHOD_ARGS]
|
||||
|
||||
# List of qualified names (i.e., library.method) which require a timeout
|
||||
# parameter e.g. 'requests.api.get,requests.api.post'
|
||||
timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request
|
||||
|
||||
|
||||
[MISCELLANEOUS]
|
||||
|
||||
# List of note tags to take in consideration, separated by a comma.
|
||||
notes=FIXME,
|
||||
XXX,
|
||||
TODO
|
||||
|
||||
# Regular expression of note tags to take in consideration.
|
||||
notes-rgx=
|
||||
|
||||
|
||||
[REFACTORING]
|
||||
|
||||
# Maximum number of nested blocks for function / method body
|
||||
max-nested-blocks=5
|
||||
|
||||
# Complete name of functions that never returns. When checking for
|
||||
# inconsistent-return-statements if a never returning function is called then
|
||||
# it will be considered as an explicit return statement and no message will be
|
||||
# printed.
|
||||
never-returning-functions=sys.exit,argparse.parse_error
|
||||
|
||||
# Let 'consider-using-join' be raised when the separator to join on would be
|
||||
# non-empty (resulting in expected fixes of the type: ``"- " + " -
|
||||
# ".join(items)``)
|
||||
suggest-join-with-non-empty-separator=yes
|
||||
|
||||
|
||||
[REPORTS]
|
||||
|
||||
# Python expression which should return a score less than or equal to 10. You
|
||||
# have access to the variables 'fatal', 'error', 'warning', 'refactor',
|
||||
# 'convention', and 'info' which contain the number of messages in each
|
||||
# category, as well as 'statement' which is the total number of statements
|
||||
# analyzed. This score is used by the global evaluation report (RP0004).
|
||||
evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10))
|
||||
|
||||
# Template used to display messages. This is a python new-style format string
|
||||
# used to format the message information. See doc for all details.
|
||||
msg-template=
|
||||
|
||||
# Set the output format. Available formats are: text, parseable, colorized,
|
||||
# json2 (improved json format), json (old json format) and msvs (visual
|
||||
# studio). You can also give a reporter class, e.g.
|
||||
# mypackage.mymodule.MyReporterClass.
|
||||
#output-format=
|
||||
|
||||
# Tells whether to display a full report or only the messages.
|
||||
reports=no
|
||||
|
||||
# Activate the evaluation score.
|
||||
score=yes
|
||||
|
||||
|
||||
[SIMILARITIES]
|
||||
|
||||
# Comments are removed from the similarity computation
|
||||
ignore-comments=yes
|
||||
|
||||
# Docstrings are removed from the similarity computation
|
||||
ignore-docstrings=yes
|
||||
|
||||
# Imports are removed from the similarity computation
|
||||
ignore-imports=yes
|
||||
|
||||
# Signatures are removed from the similarity computation
|
||||
ignore-signatures=yes
|
||||
|
||||
# Minimum lines number of a similarity.
|
||||
min-similarity-lines=4
|
||||
|
||||
|
||||
[SPELLING]
|
||||
|
||||
# Limits count of emitted suggestions for spelling mistakes.
|
||||
max-spelling-suggestions=4
|
||||
|
||||
# Spelling dictionary name. No available dictionaries : You need to install
|
||||
# both the python package and the system dependency for enchant to work.
|
||||
spelling-dict=
|
||||
|
||||
# List of comma separated words that should be considered directives if they
|
||||
# appear at the beginning of a comment and should not be checked.
|
||||
spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:
|
||||
|
||||
# List of comma separated words that should not be checked.
|
||||
spelling-ignore-words=
|
||||
|
||||
# A path to a file that contains the private dictionary; one word per line.
|
||||
spelling-private-dict-file=
|
||||
|
||||
# Tells whether to store unknown words to the private dictionary (see the
|
||||
# --spelling-private-dict-file option) instead of raising a message.
|
||||
spelling-store-unknown-words=no
|
||||
|
||||
|
||||
[STRING]
|
||||
|
||||
# This flag controls whether inconsistent-quotes generates a warning when the
|
||||
# character used as a quote delimiter is used inconsistently within a module.
|
||||
check-quote-consistency=no
|
||||
|
||||
# This flag controls whether the implicit-str-concat should generate a warning
|
||||
# on implicit string concatenation in sequences defined over several lines.
|
||||
check-str-concat-over-line-jumps=no
|
||||
|
||||
|
||||
[TYPECHECK]
|
||||
|
||||
# List of decorators that produce context managers, such as
|
||||
# contextlib.contextmanager. Add to this list to register other decorators that
|
||||
# produce valid context managers.
|
||||
contextmanager-decorators=contextlib.contextmanager
|
||||
|
||||
# List of members which are set dynamically and missed by pylint inference
|
||||
# system, and so shouldn't trigger E1101 when accessed. Python regular
|
||||
# expressions are accepted.
|
||||
generated-members=
|
||||
|
||||
# Tells whether to warn about missing members when the owner of the attribute
|
||||
# is inferred to be None.
|
||||
ignore-none=yes
|
||||
|
||||
# This flag controls whether pylint should warn about no-member and similar
|
||||
# checks whenever an opaque object is returned when inferring. The inference
|
||||
# can return multiple potential results while evaluating a Python object, but
|
||||
# some branches might not be evaluated, which results in partial inference. In
|
||||
# that case, it might be useful to still emit no-member and other checks for
|
||||
# the rest of the inferred objects.
|
||||
ignore-on-opaque-inference=yes
|
||||
|
||||
# List of symbolic message names to ignore for Mixin members.
|
||||
ignored-checks-for-mixins=no-member,
|
||||
not-async-context-manager,
|
||||
not-context-manager,
|
||||
attribute-defined-outside-init
|
||||
|
||||
# List of class names for which member attributes should not be checked (useful
|
||||
# for classes with dynamically set attributes). This supports the use of
|
||||
# qualified names.
|
||||
ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace
|
||||
|
||||
# Show a hint with possible names when a member name was not found. The aspect
|
||||
# of finding the hint is based on edit distance.
|
||||
missing-member-hint=yes
|
||||
|
||||
# The minimum edit distance a name should have in order to be considered a
|
||||
# similar match for a missing member name.
|
||||
missing-member-hint-distance=1
|
||||
|
||||
# The total number of similar names that should be taken in consideration when
|
||||
# showing a hint for a missing member.
|
||||
missing-member-max-choices=1
|
||||
|
||||
# Regex pattern to define which classes are considered mixins.
|
||||
mixin-class-rgx=.*[Mm]ixin
|
||||
|
||||
# List of decorators that change the signature of a decorated function.
|
||||
signature-mutators=
|
||||
|
||||
|
||||
[VARIABLES]
|
||||
|
||||
# List of additional names supposed to be defined in builtins. Remember that
|
||||
# you should avoid defining new builtins when possible.
|
||||
additional-builtins=
|
||||
|
||||
# Tells whether unused global variables should be treated as a violation.
|
||||
allow-global-unused-variables=yes
|
||||
|
||||
# List of names allowed to shadow builtins
|
||||
allowed-redefined-builtins=
|
||||
|
||||
# List of strings which can identify a callback function by name. A callback
|
||||
# name must start or end with one of those strings.
|
||||
callbacks=cb_,
|
||||
_cb
|
||||
|
||||
# A regular expression matching the name of dummy variables (i.e. expected to
|
||||
# not be used).
|
||||
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
|
||||
|
||||
# Argument names that match this expression will be ignored.
|
||||
ignored-argument-names=_.*|^ignored_|^unused_
|
||||
|
||||
# Tells whether we should check for unused import in __init__ files.
|
||||
init-import=no
|
||||
|
||||
# List of qualified module names which can have objects that can redefine
|
||||
# builtins.
|
||||
redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
|
||||
|
||||
+10
-7
@@ -1,7 +1,10 @@
|
||||
openai==0.27
|
||||
termcolor==2.2.0
|
||||
colorama==0.4.4
|
||||
python-dotenv==1.0.0
|
||||
distro==1.7.0
|
||||
PyYAML==5.4.1
|
||||
pyperclip==1.8.2
|
||||
ollama==0.2.1
|
||||
openai==1.35.7
|
||||
termcolor==2.4.0
|
||||
colorama==0.4.6
|
||||
python-dotenv==1.0.1
|
||||
distro==1.9.0
|
||||
PyYAML==6.0.1
|
||||
pyperclip==1.9.0
|
||||
groq==0.9.0
|
||||
anthropic==0.30.0
|
||||
|
||||
+21
-28
@@ -1,31 +1,24 @@
|
||||
Act as a natural language to {shell} command translation engine on {os}.
|
||||
You are Yolo, a natural language to {shell} command translation engine for {os}. You are an expert in {shell} on {os} and translate the question at the end to valid command line syntax.
|
||||
|
||||
You are an expert in {shell} on {os} and translate the question at the end to valid syntax.
|
||||
Rules:
|
||||
* Output in plain text only, no code style markdown.
|
||||
* Construct a valid {shell} command to solve the question.
|
||||
* Use help and man pages to ensure correct syntax and an optimal solution.
|
||||
* Be concise, think sequentially, and show only the final commands in plain text.
|
||||
* Provide a single answer, using chained commands if necessary.
|
||||
* Ensure the syntax is valid for {shell} on {os}, including comments if useful.
|
||||
* You may use Python or Python3 if installed to solve problems.
|
||||
* Even with minimal details, determine the most logical solution step by step.
|
||||
* Do not return multiple solutions.
|
||||
* Avoid HTML, styled, or coloured formatting.
|
||||
* Ensure no invalid syntax or syntax errors.
|
||||
* Do not include extraneous text in the response.
|
||||
* Do not add notes or introductory sentences.
|
||||
* Do not return the question.
|
||||
* Do not reiterate or paraphrase the question.
|
||||
* Do not rush to conclusions.
|
||||
* Responses should never begin with ```
|
||||
|
||||
Follow these rules:
|
||||
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 by going about it step by step
|
||||
Do not return multiple solutions
|
||||
Do not show html, styled, colored formatting
|
||||
Do not creating invalid syntax
|
||||
Do not add unnecessary text in the response
|
||||
Do not add notes or intro sentences
|
||||
Do not show multiple distinct solutions to the question
|
||||
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 cause syntax errors
|
||||
Do not rush to a conclusion
|
||||
Follow these rules without exception.
|
||||
|
||||
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.
|
||||
|
||||
Question:
|
||||
Question:
|
||||
|
||||
@@ -15,6 +15,7 @@ of every command or script they frequently use.
|
||||
Sources:
|
||||
— https://github.com/wunderwuzzi23/yolo-ai-cmdbot
|
||||
"""
|
||||
|
||||
import os
|
||||
import platform
|
||||
import subprocess
|
||||
@@ -30,9 +31,12 @@ import yaml
|
||||
from termcolor import colored
|
||||
from colorama import init
|
||||
|
||||
from ai_model import AIModel
|
||||
|
||||
CONFIG_FILE = "yolo.yaml"
|
||||
PROMPT_FILE = "yolo.prompt"
|
||||
|
||||
|
||||
def read_yaml_config() -> any:
|
||||
"""
|
||||
Read the configuration file from the executing directory.
|
||||
@@ -49,9 +53,10 @@ def read_yaml_config() -> any:
|
||||
prompt_path = os.path.dirname(yolo_path)
|
||||
|
||||
config_file = os.path.join(prompt_path, CONFIG_FILE)
|
||||
with open(config_file, 'r') as file:
|
||||
with open(config_file, "r", encoding="utf-8") as file:
|
||||
return yaml.safe_load(file)
|
||||
|
||||
|
||||
def set_openai_api_key(config):
|
||||
"""
|
||||
Set the OpenAI API key by attempting several methods.
|
||||
@@ -87,6 +92,7 @@ def set_openai_api_key(config):
|
||||
if not openai.api_key:
|
||||
openai.api_key = config["openai_api_key"]
|
||||
|
||||
|
||||
def print_config(config):
|
||||
"""
|
||||
Print config information.
|
||||
@@ -102,12 +108,16 @@ def print_config(config):
|
||||
the following keys: "model", "temperature", "max_tokens", "safety", "shell".
|
||||
"""
|
||||
print("Current configuration per yolo.yaml:")
|
||||
print("— API : " + str(config["api"]))
|
||||
print("— Model : " + str(config["model"]))
|
||||
print("— Temperature : " + str(config["temperature"]))
|
||||
print("— Max. Tokens : " + str(config["max_tokens"]))
|
||||
print("— Safety : " + str(bool(config["safety"])))
|
||||
print("— Modify : " + str(bool(config["modify"])))
|
||||
print("— Color : " + str(config["suggested_command_color"]))
|
||||
print("— Shell : " + str(config["shell"]))
|
||||
|
||||
|
||||
def get_os_friendly_name():
|
||||
"""
|
||||
Returns a friendly name of the user's operating system.
|
||||
@@ -135,73 +145,87 @@ def get_os_friendly_name():
|
||||
|
||||
return os_name
|
||||
|
||||
def get_full_prompt(user_prompt, shell):
|
||||
"""
|
||||
Constructs a full prompt string by appending the user's prompt to a predefined prompt template
|
||||
located in the PROMPT_FILE file.
|
||||
|
||||
The function finds the absolute path of the currently executing file, and based on this path,
|
||||
identifies the directory of PROMPT_FILE. It reads this file, replaces placeholders {shell}
|
||||
and {os} in the text file with a passed shell parameter and the friendly name of the operating
|
||||
system respectively. The user prompt is then appended to this pre-prompt. If the resulting
|
||||
prompt does not end with a question mark or a period, a question mark is added at last.
|
||||
def get_system_prompt(shell):
|
||||
"""
|
||||
Retrieves and constructs a system prompt by replacing placeholders
|
||||
in a predefined template with specific values.
|
||||
|
||||
The function finds the absolute path of the currently executing file
|
||||
and, based on this path, identifies the directory of PROMPT_FILE.
|
||||
It reads the file and replaces the placeholders {shell} and {os}
|
||||
with the provided shell parameter and the friendly name of the operating system, respectively.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
user_prompt : str
|
||||
The prompt supplied by the user to be appended to the pre-prompt.
|
||||
The user's prompt (not used in this function, included for context in future use).
|
||||
shell : str
|
||||
The shell information to be inserted in the place of {shell} placeholder in PROMPT_FILE.
|
||||
The shell information to be inserted in place of the {shell} placeholder in PROMPT_FILE.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
The full prompt, constructed from the template prompt in PROMPT_FILE,
|
||||
user-provided shell info, the OS name, and the user-supplied prompt string.
|
||||
The system prompt, constructed from the template prompt in PROMPT_FILE
|
||||
with the shell and OS placeholders replaced with actual values.
|
||||
"""
|
||||
yolo_path = os.path.abspath(__file__)
|
||||
prompt_path = os.path.dirname(yolo_path)
|
||||
|
||||
## Load the prompt and prep it
|
||||
prompt_file = os.path.join(prompt_path, PROMPT_FILE)
|
||||
pre_prompt = open(prompt_file,"r").read()
|
||||
pre_prompt = pre_prompt.replace("{shell}", shell)
|
||||
pre_prompt = pre_prompt.replace("{os}", get_os_friendly_name())
|
||||
prompt = pre_prompt + user_prompt
|
||||
with open(prompt_file, "r", encoding="utf-8") as file:
|
||||
system_prompt = file.read()
|
||||
system_prompt = system_prompt.replace("{shell}", shell)
|
||||
system_prompt = system_prompt.replace("{os}", get_os_friendly_name())
|
||||
|
||||
# Be nice and make it a question.
|
||||
if prompt[-1:] != "?" and prompt[-1:] != ".":
|
||||
prompt+="?"
|
||||
return system_prompt
|
||||
|
||||
return prompt
|
||||
|
||||
def call_open_ai(config, query):
|
||||
def chat_completion(client, query, config):
|
||||
"""
|
||||
Do we have a prompt from the user?
|
||||
Generate a chat-based completion for a given query using a specified model.
|
||||
|
||||
This function sends a user query to a chat model and returns the generated response.
|
||||
|
||||
Parameters:
|
||||
client (object): The client object to interact with the chat service.
|
||||
query (str): The user's query to send to the chat model.
|
||||
config (dict): Configuration settings for the chat service, which should include:
|
||||
- "shell" (str): Type of shell to use in the system prompt.
|
||||
- "model" (str): The specific model to use for the chat completion.
|
||||
- "temperature" (float): Sampling temperature to use for the response generation (higher
|
||||
values mean the model will take more risks).
|
||||
- "max_tokens" (int): Maximum number of tokens to generate in the chat response.
|
||||
|
||||
Returns:
|
||||
dict: The response from the chat model.
|
||||
|
||||
Raises:
|
||||
SystemExit: If the query is an empty string, the function will print an error message and exit.
|
||||
"""
|
||||
if query == "":
|
||||
print ("No user prompt specified.")
|
||||
print("No user prompt specified.")
|
||||
sys.exit(-1)
|
||||
|
||||
# Load the correct prompt based on shell and OS and append the user's prompt.
|
||||
prompt = get_full_prompt(query, config["shell"])
|
||||
system_prompt = get_system_prompt(config["shell"])
|
||||
|
||||
# Make the first line also the system prompt
|
||||
system_prompt = prompt[1]
|
||||
#print(prompt)
|
||||
# Ensure query is a question
|
||||
if query[-1:] != "?" and query[-1:] != ".":
|
||||
query += "?"
|
||||
|
||||
# Call the ChatGPT API
|
||||
response = openai.ChatCompletion.create(
|
||||
response = client.chat(
|
||||
model=config["model"],
|
||||
messages=[
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": prompt}
|
||||
{"role": "user", "content": query},
|
||||
],
|
||||
temperature=config["temperature"],
|
||||
max_tokens=config["max_tokens"],
|
||||
)
|
||||
|
||||
return response.choices[0].message.content.strip()
|
||||
return response
|
||||
|
||||
|
||||
def check_for_issue(response):
|
||||
"""
|
||||
@@ -218,9 +242,10 @@ def check_for_issue(response):
|
||||
"""
|
||||
prefixes = ("sorry", "i'm sorry", "the question is not clear", "i'm", "i am")
|
||||
if response.lower().startswith(prefixes):
|
||||
print(colored("There was an issue: "+response, 'red'))
|
||||
print(colored("There was an issue: " + response, "red"))
|
||||
sys.exit(-1)
|
||||
|
||||
|
||||
def check_for_markdown(response):
|
||||
"""
|
||||
Checks for the presence of markdown formatting (specifically, code snippet markdown) in the
|
||||
@@ -236,12 +261,17 @@ def check_for_markdown(response):
|
||||
response : str
|
||||
A response text string that needs to be examined for markdown formatting.
|
||||
"""
|
||||
if response.count("```",2):
|
||||
print(colored(
|
||||
"The proposed command contains markdown, response not executed directly: \n", 'red'
|
||||
) + response)
|
||||
if response.count("```", 2):
|
||||
print(
|
||||
colored(
|
||||
"The proposed command contains markdown, response not executed directly: \n",
|
||||
"red",
|
||||
)
|
||||
+ response
|
||||
)
|
||||
sys.exit(-1)
|
||||
|
||||
|
||||
def missing_posix_display():
|
||||
"""
|
||||
Checks if the DISPLAY environment variable is set in a POSIX-compliant shell.
|
||||
@@ -258,7 +288,8 @@ def missing_posix_display():
|
||||
"""
|
||||
display = subprocess.check_output("echo $DISPLAY", shell=True)
|
||||
|
||||
return display == b'\n'
|
||||
return display == b"\n"
|
||||
|
||||
|
||||
def prompt_user_input(config, response):
|
||||
"""
|
||||
@@ -279,15 +310,25 @@ def prompt_user_input(config, response):
|
||||
response : str
|
||||
The proposed command which is to be printed and may be executed by the user.
|
||||
"""
|
||||
print("Command: " + colored(response, 'blue'))
|
||||
print(
|
||||
"Command: "
|
||||
+ colored(response, config["suggested_command_color"], attrs=["bold"])
|
||||
)
|
||||
|
||||
if config["safety"]:
|
||||
prompt_text = "Execute command? [Y]es [n]o [m]odify [c]opy to clipboard ==> "
|
||||
modify_text = ""
|
||||
|
||||
if config["modify"]:
|
||||
modify_text = " [m]modify"
|
||||
|
||||
prompt_text = (
|
||||
"Execute command? [Y]es [n]o [c]opy to clipboard" + modify_text + ": "
|
||||
)
|
||||
|
||||
if os.name == "posix" and missing_posix_display():
|
||||
prompt_text = "Execute command? [Y]es [n]o [m]odify ==> "
|
||||
prompt_text = "Execute command? [Y]es [n]o" + modify_text + ": "
|
||||
|
||||
print(prompt_text, end = '')
|
||||
print(prompt_text, end="")
|
||||
|
||||
user_input = input()
|
||||
else:
|
||||
@@ -295,7 +336,8 @@ def prompt_user_input(config, response):
|
||||
|
||||
return user_input
|
||||
|
||||
def evaluate_input(config, user_input, command):
|
||||
|
||||
def evaluate_input(client, config, user_input, command):
|
||||
"""
|
||||
Evaluate the user input to either execute, modify, or copy the command.
|
||||
|
||||
@@ -324,14 +366,14 @@ def evaluate_input(config, user_input, command):
|
||||
subprocess.run([config["shell"], "-c", command], shell=False, check=True)
|
||||
|
||||
if user_input.upper() == "M":
|
||||
print("Modify prompt: ", end = '')
|
||||
print("Modify prompt: ", end="")
|
||||
modded_query = input()
|
||||
modded_response = call_open_ai(config, modded_query)
|
||||
modded_response = chat_completion(client, modded_query, config)
|
||||
check_for_issue(modded_response)
|
||||
check_for_markdown(modded_response)
|
||||
modded_user_input = prompt_user_input(config, modded_response)
|
||||
print()
|
||||
evaluate_input(config, modded_user_input, modded_response)
|
||||
evaluate_input(client, config, modded_user_input, modded_response)
|
||||
|
||||
if user_input.upper() == "C":
|
||||
if os.name == "posix" and missing_posix_display():
|
||||
@@ -345,18 +387,23 @@ def main():
|
||||
Defined starting point of source code.
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
description='AI bot that translates your question to a command.'
|
||||
description="AI bot that translates your question to a command."
|
||||
)
|
||||
parser.add_argument("text", nargs="+", help="A sequence of strings")
|
||||
parser.add_argument(
|
||||
"-s",
|
||||
"--safety",
|
||||
action="store_true",
|
||||
help="Enable safety mode (only useful when safety is off)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-c", "--config", action="store_true", help="Print current configuration"
|
||||
)
|
||||
parser.add_argument('text', nargs='+',
|
||||
help='A sequence of strings')
|
||||
parser.add_argument("-s", "--safety", action='store_true',
|
||||
help='Enable safety mode (only useful when safety is off)')
|
||||
parser.add_argument("-c", "--config", action='store_true',
|
||||
help='Print current configuration')
|
||||
args = parser.parse_args()
|
||||
|
||||
# Load configuration
|
||||
# Load configurations and set up client
|
||||
config = read_yaml_config()
|
||||
client = AIModel.get_model_client(config)
|
||||
set_openai_api_key(config)
|
||||
|
||||
# Process parameters
|
||||
@@ -374,12 +421,14 @@ def main():
|
||||
# Enable color output on Windows using colorama
|
||||
init()
|
||||
|
||||
res_command = call_open_ai(config, user_prompt)
|
||||
check_for_issue(res_command)
|
||||
check_for_markdown(res_command)
|
||||
user_input = prompt_user_input(config, res_command)
|
||||
result = chat_completion(client, user_prompt, config)
|
||||
check_for_issue(result)
|
||||
check_for_markdown(result)
|
||||
|
||||
user_input = prompt_user_input(config, result)
|
||||
print()
|
||||
evaluate_input(config, user_input, res_command)
|
||||
evaluate_input(client, config, user_input, result)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -1,9 +1,22 @@
|
||||
model: gpt-3.5-turbo # If you have access to gpt-4 API already, you can update this.
|
||||
api: openai # openai, azure, groq, ollama, anthropic
|
||||
model: gpt-4o # if azure this is the deployment name
|
||||
# other options: gpt-4o, llama3-8b-8192, or claude-3-5-sonnet-20240620
|
||||
|
||||
# Azure specific (only needed if api: azure-openai)
|
||||
azure_endpoint: https://<name>.openai.azure.com
|
||||
azure_api_version: 2024-02-15-preview
|
||||
|
||||
# Completion parameters
|
||||
temperature: 0
|
||||
max_tokens: 500
|
||||
|
||||
# Safety: If set to False, commands returned from the AI will be run *without* prompting the user.
|
||||
safety: True
|
||||
safety: True # Safety: If set to False, commands from LLM run *without* prompting the user.
|
||||
modify: False # Enable prompt modify feature
|
||||
suggested_command_color: blue # Suggested Command Color
|
||||
|
||||
# Open AI API Key (optional): The key can aso be provided via environment variable (OPENAI_API_KEY), .env, or ~/.openai.apikey file
|
||||
openai_api_key:
|
||||
# API Keys (optional): Preferred to use environment variables
|
||||
# OPENAI_API_KEY, AZURE_OPENAI_API_KEY, ANTHROPIC_API_KEY or GROQ_API_KEY (.env file is also supported)
|
||||
azure_openai_api_key:
|
||||
openai_api_key:
|
||||
groq_api_key:
|
||||
anthropic_api_key:
|
||||
Reference in New Issue
Block a user