31 Commits

Author SHA1 Message Date
schihei 21ca4378df Beautified source code with Black 2024-08-20 11:27:30 +02:00
schihei 48c77403a3 Updated pylintrc file 2024-08-19 22:31:01 +02:00
schihei e0f88630e6 Fixed all pylint warnings 2024-08-19 22:30:42 +02:00
schihei 88167486ab Added command colour configuration 2024-08-19 22:09:59 +02:00
schihei 5bbc423840 Usage of modify configuration 2024-08-19 22:03:55 +02:00
schihei 9610525ecb Fixed simple pylint warnings 2024-08-19 19:29:59 +02:00
schihei 0a5769f8a0 Changed source code documentation for get_system_prompt function 2024-08-19 19:20:35 +02:00
schihei 7cfc47cdc3 Added debug output for new configurations 2024-08-19 19:17:52 +02:00
schihei 256b616f02 Fir changes after version was increased to 0.5 2024-08-19 19:09:47 +02:00
schihei 84a8876016 Updated system prompt 2024-08-18 22:32:29 +02:00
Heiko Joerg Schick 20c2a112aa Minor changes 2023-09-06 15:37:49 +02:00
Heiko Joerg Schick ee96b7822d Minor file name changes 2023-09-06 15:35:34 +02:00
Heiko Joerg Schick 689813e664 Minor changes in whitespaces 2023-09-05 22:42:27 +02:00
Heiko Joerg Schick 56e4f8e7a5 Add a file conversation 2023-09-05 22:40:58 +02:00
Heiko Joerg Schick 8e8b1c4181 Added constant for prompt file 2023-09-05 22:38:19 +02:00
Heiko Joerg Schick a3e4209d1e Renamed prompt.txt to yolo.prompt 2023-09-05 22:36:04 +02:00
Heiko Joerg Schick 79b6de19f2 Added more documentation information for residual functions 2023-09-05 22:32:55 +02:00
Heiko Joerg Schick 51de9db4ea Minor changes 2023-09-05 21:26:02 +02:00
Heiko Joerg Schick ea21e18bee Minor modification 2023-09-05 21:24:20 +02:00
Heiko Joerg Schick bc1e997708 Removed all pylint warnings 2023-09-05 21:11:23 +02:00
Heiko Joerg Schick 838d55563b Improved boolean operators 2023-09-05 20:52:54 +02:00
Heiko Joerg Schick 1567fb40ea White space clean up and simplification of get_os_friendly_name. 2023-09-05 20:43:08 +02:00
Heiko Joerg Schick dece99ba87 Argument parsing via argparse 2023-09-05 20:29:38 +02:00
Heiko Joerg Schick a5d60f6fff Added pylintrc 2023-09-05 19:59:33 +02:00
Heiko Joerg Schick ed65b2ab4b Improved coding style and comment for read_yaml_config and set_openai_api_key function 2023-09-05 14:48:54 +02:00
Heiko Joerg Schick 34eb29b926 Moved entry functional calls to main and got rid of global config variable 2023-09-05 11:37:23 +02:00
Heiko Joerg Schick f6644f7717 Added main entry point 2023-09-05 11:14:05 +02:00
Heiko Joerg Schick 130e0b0ae2 Standard imports needs to be placed before package imports 2023-09-05 10:53:19 +02:00
Heiko Joerg Schick f8636d3e03 Added missing function docstring 2023-09-05 10:51:58 +02:00
Heiko Joerg Schick e2fbee6de4 Fixed bad indentation
Please enter the commit message for your changes. Lines starting
2023-09-05 10:35:06 +02:00
Heiko Joerg Schick f43900631a Remove trailing white spaces 2023-09-05 10:25:51 +02:00
10 changed files with 1157 additions and 295 deletions
+12 -43
View File
@@ -10,19 +10,19 @@
# 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 `llama3-8b-8192`. groq is lightning fast.
* 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 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.
* Key changes are upgrades to the latest OpenAI libraries and
# Update Yolo v0.2 - Support for GPT-4 API
@@ -31,18 +31,16 @@ This update introduces the `yolo.yaml` configuration file. In this file you can
For now the default model is still `gpt-3.5-turbo`, but you can update to `gpt-4` if you have gotten access already!
```
Yolo v0.3 - by @wunderwuzzi23
Yolo v0.2 - by @wunderwuzzi23
Usage: yolo [-a] list the current directory information
Argument: -a: Prompt the user before running the command (only useful when safety is off)
Current configuration per yolo.yaml:
* API : openai
* Model : gpt-4-turbo-preview
* Model : gpt-3.5-turbo
* Temperature : 0
* Max. Tokens : 500
* Safety : True
* Command Color: blue
* Safety : on
```
Happy Hacking!
@@ -65,18 +63,7 @@ yolo show me some funny unicode characters
There are three ways to configure the key on Linux and macOS:
- You can either `export OPENAI_API_KEY=<yourkey>`, or have a `.env` file in the same directory as `yolo.py` with `OPENAI_API_KEY="<yourkey>"` as a line
- Create a file at `~/.openai.apikey` with the key in it
- Set the key in the `yolo.yaml` configuration file
### Azure OpenAI Key configuration
There are three ways to configure the key on Linux and macOS:
- You can either `export AZURE_OPENAI_API_KEY=<yourkey>`, or have a `.env` file in the same directory as `yolo.py` with `AZURE_OPENAI_API_KEY="<yourkey>"` as a line
- Create a file at `~/.azureopenai.apikey` with the key in it
- Set the key in the `yolo.yaml` configuration file
### Groq Configuration
- Grab an API key from `console.groq.com`
- You can either `export GROQ_API_KEY=<yourkey>`, or have a `.env` file in the same directory as `yolo.py` with `GROQ_API_KEY="<yourkey>"` as a line
- Set `api` and `model` (e.g llama3-8b-8192) in `yolo.yaml` configuration file
- Add the key to the `yolo.yaml` configuration file
## Aliases
@@ -109,22 +96,6 @@ You also have the option to:
That's it basically.
### PowerShell Command
If you want a PowerShell style command you can use something like this (check that the path is to yolo.py is correct) and you can add this function to your PowerShell profile.
```
function Invoke-Yolo {
param([Parameter(ValueFromRemainingArguments=$true)]$Commands)
$AllCommands = $Commands -join " "
$YoloPath = Join-Path -Path $env:USERPROFILE -ChildPath "\yolo-ai-cmdbot\yolo.py"
python.exe $YoloPath $AllCommands
}
```
You can find the profile file with `$PROFILE` in a PowerShell Terminal. I might add a better installation in future.
## OpenAI API Key Configuration on Windows
On Windows `export OPENAI_API_KEY=<yourkey>` will not work instead:
@@ -134,8 +105,6 @@ On Windows `export OPENAI_API_KEY=<yourkey>` will not work instead:
Optionally (since v.0.2), the key can also be stored in `yolo.yaml`.
If you want to use Azure, the the key is called `AZURE_OPENAI_API_KEY`.
## Running yolo on Windows
Windows is less tested, it does work though and will use PowerShell.
@@ -170,7 +139,7 @@ Since v.0.2 the safety switch setting moved to `yolo.yaml`, the old `~/.yolo-saf
To have yolo run commands right away when they come back from ChatGPT change the `safety` in the `yolo.yaml` to `False`.
If you still want to inspect the command that is executed when safety is off, add the `-a` argument, e.g `yolo -a delete the file test.txt`.
If you still want to inspect the command that is executed when safety is off, add the `-s` argument, e.g `yolo -s delete the file test.txt`.
Let's go!
+81 -60
View File
@@ -1,15 +1,12 @@
# MIT License
# Copyright (c) 2023-2024 wunderwuzzi23
# Greetings from Seattle!
from abc import ABC, abstractmethod
from openai import OpenAI
from groq import Groq
from ollama import Client
from openai import AzureOpenAI
from openai import AzureOpenAI
from anthropic import Anthropic
import os
class AIModel(ABC):
@abstractmethod
def chat(self, model, messages):
@@ -21,109 +18,129 @@ class AIModel(ABC):
@staticmethod
def get_model_client(config):
api_provider=config["api"]
api_provider = config["api"]
if api_provider == "" or api_provider==None:
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()
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()
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"])
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")
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)
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)
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)
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)
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)
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)
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)
@@ -131,19 +148,23 @@ class AnthropicModel(AIModel):
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
## 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"), "")
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)
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 -5
View File
@@ -3,9 +3,8 @@ setlocal enabledelayedexpansion
:: First check if `install.bat` (this) has needed files in same directory
if not exist %~dp0\yolo.py ( echo `yolo.py` missing in %~dp0 cannot install & goto :choice_default_3 )
if not exist %~dp0\prompt.txt ( echo `prompt.txt` missing in %~dp0 cannot install & goto :choice_default_3 )
if not exist %~dp0\yolo.prompt ( echo `yolo.prompt` missing in %~dp0 cannot install & goto :choice_default_3 )
if not exist %~dp0\yolo.yaml ( echo `yolo.yaml` missing in %~dp0 cannot install & goto :choice_default_3 )
if not exist %~dp0\ai_model.py ( echo `ai_model.py` missing in %~dp0 cannot install & goto :choice_default_3 )
:: Note: "~" or %HOME% is equivalent to "%HOMEDRIVE%%HOMEPATH%\" but the latter is set in VM environments (from what I can tell)
@@ -138,7 +137,6 @@ mkdir !TARGET_DIR!
copy %~dp0\yolo.py !TARGET_DIR!
copy %~dp0\prompt.txt !TARGET_DIR!
copy %~dp0\yolo.yaml !TARGET_DIR!
copy %~dp0\ai_model.py !TARGET_DIR!
goto :EOF
:: Create yolo.bat and input code linking to created directory
@@ -314,6 +312,4 @@ echo -If you run PowerShell as administrator you can then run `setx OPENAI_API
echo -Go to `Start` and search `edit environment variables for your account` and manually create the variable with name `OPENAI_API_KEY` and value `[yourkey]`
echo (4) Another option is to put the API key in the yolo.yaml configuration file (since v.0.2)
echo.
echo Yolo also supports Azure OpenAI, and many other LLMs now. Configure settings in yolo.yaml accordingly.
echo.
goto :EOF
+3 -5
View File
@@ -7,7 +7,7 @@ TARGET_FULLPATH=$TARGET_DIR/yolo.py
mkdir -p $TARGET_DIR
echo "- Copying files..."
cp yolo.py prompt.txt yolo.yaml ai_model.py $TARGET_DIR
cp yolo.py yolo.prompt yolo.yaml $TARGET_DIR
chmod +x $TARGET_FULLPATH
# Creates two aliases for use
@@ -34,11 +34,9 @@ fi
echo
echo "Done."
echo
echo "Make sure you have your LLM key (e.g. OpenAI API) set via one of these options:"
echo "Make sure you have the OpenAI API key set via one of these options:"
echo " - environment variable"
echo " - .env or in"
echo " - .env or an ~/.openai.apikey file or in"
echo " - yolo.yaml"
echo
echo "Yolo also supports Azure OpenAI, Ollama, groq, Claude now. Change settings in yolo.yaml accordingly."
echo
echo "Have fun!"
-26
View File
@@ -1,26 +0,0 @@
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.
Rules:
* No code style markdown output, ever.
* Construct valid {shell} command to solve the question
* Leverage help and man pages to ensure valid syntax and an optimal solution
* Be concise, think step by step, and show just final commands in plain text
* Only show a single answer, but you can always chain commands together
* Create valid syntax of {shell} on {os}, include comments if useful
* If python or python3 is installed you can use it to solve problems
* Even if there is a lack of details, 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 create invalid syntax or cause syntax errors
* 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 rush to a conclusion
* Never start a response with ```
Follow above rules. There are no exceptions to these rules.
Question:
+644
View File
@@ -0,0 +1,644 @@
[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=
# 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=
# 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 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, and will cap the count on Windows to
# avoid hangs.
jobs=1
# Control the amount of potential inferred values when inferring a single
# object. This can help the performance when dealing with large functions or
# complex, nested conditions.
limit-inference-results=100
# List of plugins (as comma separated values of python module names) to load,
# usually to register additional checkers.
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
# Allow loading of arbitrary C extensions. Extensions are imported into the
# active Python interpreter and may run arbitrary code.
unsafe-load-any-extension=no
# In verbose mode, extra non-checker-related info will be displayed.
#verbose=
[BASIC]
# Naming style matching correct argument names.
argument-naming-style=snake_case
# Regular expression matching correct argument names. Overrides argument-
# 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=
# Bad variable names which should always be refused, separated by a comma.
bad-names=foo,
bar,
baz,
toto,
tutu,
tata
# Bad variable names regexes, separated by a comma. If names match any regex,
# they will always be refused
bad-names-rgxs=
# Naming style matching correct class attribute names.
class-attribute-naming-style=any
# Regular expression matching correct class attribute names. Overrides class-
# 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. 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=
# Minimum line length for functions/classes that require docstrings, shorter
# ones are exempt.
docstring-min-length=-1
# Naming style matching correct function names.
function-naming-style=snake_case
# Regular expression matching correct function names. Overrides function-
# 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.
good-names=i,
j,
k,
ex,
Run,
_
# Good variable names regexes, separated by a comma. If names match any regex,
# they will always be accepted
good-names-rgxs=
# Include a hint for the correct naming format with invalid-name.
include-naming-hint=no
# Naming style matching correct inline iteration names.
inlinevar-naming-style=any
# Regular expression matching correct inline iteration names. Overrides
# 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. 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. 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
# the name regexes allow several styles.
name-group=
# Regular expression which should only match function or class names that do
# not require a docstring.
no-docstring-rgx=^_
# List of decorators that produce properties, such as abc.abstractproperty. Add
# to this list to register other decorators that produce valid properties.
# 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. If left empty, variable names will be checked with the set
# naming style.
#variable-rgx=
[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,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=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
# Maximum number of attributes for a class (see R0902).
max-attributes=7
# Maximum number of boolean expressions in an if statement (see R0916).
max-bool-expr=5
# Maximum number of branch for function / method body.
max-branches=12
# Maximum number of locals for function / method body.
max-locals=15
# Maximum number of parents for a class (see R0901).
max-parents=7
# Maximum number of public methods for a class (see R0904).
max-public-methods=20
# Maximum number of return / yield for function / method body.
max-returns=6
# Maximum number of statements in function / method body.
max-statements=50
# Minimum number of public methods for a class (see R0903).
min-public-methods=2
[EXCEPTIONS]
# 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
+1 -1
View File
@@ -7,4 +7,4 @@ distro==1.9.0
PyYAML==6.0.1
pyperclip==1.9.0
groq==0.9.0
anthropic==0.30.0
anthropic==0.30.0
+24
View File
@@ -0,0 +1,24 @@
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.
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 without exception.
Question:
+390 -154
View File
@@ -1,198 +1,434 @@
#!/usr/bin/env python3
"""
AI Chatbot to generate shell commands.
# MIT License
# Copyright (c) 2023-2024 wunderwuzzi23
# Greetings from Seattle!
This script allows the user to ask their question in plain English and translates
that question into a command that can be run in the shell. The functionalities
include leveraging OpenAI's GPT models to generate command, verifying newly generated
commands, checking commands for any unsafe attributes, and allowing the user to
execute or modify the generated command.
This program is an implementation of an AI model used to assist users in
generating Unix/shell commands or other scripts, based on their natural language
input. The objective is to aid those users who might not remember the exact syntax
of every command or script they frequently use.
Sources:
— https://github.com/wunderwuzzi23/yolo-ai-cmdbot
"""
import os
import platform
from ai_model import AIModel, GroqModel, OpenAIModel, OllamaModel, AnthropicModel, AzureOpenAIModel
import sys
import subprocess
import dotenv
import sys
import argparse
import distro
import yaml
import dotenv
import openai
import pyperclip
import yaml
from termcolor import colored
from colorama import init
def read_config():
## Find the executing directory (e.g. in case an alias is set)
## So we can find the config file
yolo_path = os.path.abspath(__file__)
prompt_path = os.path.dirname(yolo_path)
from ai_model import AIModel
config_file = os.path.join(prompt_path, "yolo.yaml")
with open(config_file, 'r') as file:
return yaml.safe_load(file)
CONFIG_FILE = "yolo.yaml"
PROMPT_FILE = "yolo.prompt"
def get_system_prompt(shell):
## Find the executing directory (e.g. in case an alias is set)
## So we can find the prompt.txt file
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.txt")
system_prompt = open(prompt_file,"r").read()
system_prompt = system_prompt.replace("{shell}", shell)
system_prompt = system_prompt.replace("{os}", get_os_friendly_name())
def read_yaml_config() -> any:
"""
Read the configuration file from the executing directory.
return system_prompt
This function determines the execution folder (which may vary if an alias is set) in order to
find the configuration file. It reads the file and returns its content in a Python data
structure.
def ensure_prompt_is_question(prompt):
if prompt[-1:] != "?" and prompt[-1:] != ".":
prompt+="?"
return prompt
Returns:
The content of the configuration file. Could be dictionary, list, etc. depending on
the YAML file structure.
"""
yolo_path = os.path.abspath(__file__)
prompt_path = os.path.dirname(yolo_path)
def print_usage(config):
print("Yolo v0.5 - by @wunderwuzzi23 (June 29, 2024)")
print()
print("Usage: yolo [-a] list the current directory information")
print("Argument: -a: Prompt the user before running the command (only useful when safety is off)")
print()
config_file = os.path.join(prompt_path, CONFIG_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.
This function first tries to grab the OpenAI API key from environment variables,
if not found, it then looks for the key in the `.openai.apikey` in the home directory,
and lastly, it will look in the provided config dictionary. It sets the `openai.api_key`
with the retrieved key.
Parameters:
config (dict): A dictionary containing configuration values.
It may contain `openai_api_key` as one of the keys.
"""
dotenv.load_dotenv()
# Method 1: Read API key from environment variable
# The user can set their OpenAI API key by creating a ".env" file in the same
# directory as this script or by exporting it to their environment variables.
# The file or environment variable should contain the line `OPENAI_API_KEY="<yourkey>"`.
config["openai_api_key"] = os.getenv("OPENAI_API_KEY")
# Method 2: Read API key from a file in the home directory
# The user can also place a file named ".openai.apikey" in their home directory,
# which includes the API key in raw format. This method might be deprecated in future versions.
if not openai.api_key: # Check this to avoid potential "invalid filepath" error.
home_path = os.path.expanduser("~")
openai.api_key_path = os.path.join(home_path, ".openai.apikey")
# Method 3: Read API key from the provided config dictionary
# The final method to set the API key is by providing it in the 'config' dictionary under the
# key 'openai_api_key'. For instance, in a `yolo.yaml` config file, it would appear as
# `openai_apikey: <yourkey>`.
if not openai.api_key:
openai.api_key = config["openai_api_key"]
def print_config(config):
"""
Print config information.
Given an input configuration dictionary, this function prints out the
current configurations per yolo.yaml. This includes details on "model",
"temperature", "max_tokens", "safety", and "shell".
Parameters
----------
config : dict
A dictionary containing the various configuration parameters. It should have
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"]))
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("* Command Color: " + str(config["suggested_command_color"]))
def get_os_friendly_name():
os_name = platform.system()
"""
Returns a friendly name of the user's operating system.
The function retrieves the current system platform name using the `platform.system()` function.
For Linux, it appends the distribution name retrieved from `distro.name(pretty=True)` to give a
more descriptive representation. For Darwin (Apple's macOS), it appends "macOS" to "Darwin" to
make the output clearer to the user.
Returns
-------
str
A friendly name for the user's operating system. It will be one of the following:
- "Linux/<distribution name>"
- "Darwin/macOS"
- The system string returned by `platform.system()` if it's not Linux or Darwin.
"""
os_name = platform.system()
if os_name == "Linux":
os_name = "Linux/" + distro.name(pretty=True)
elif os_name == "Darwin":
os_name = "Darwin/macOS"
if os_name == "Linux":
return "Linux/"+distro.name(pretty=True)
elif os_name == "Windows":
return os_name
elif os_name == "Darwin":
return "Darwin/macOS"
else:
return os_name
def chat_completion(client, query, config, shell):
if query == "":
print ("No user prompt specified.")
sys.exit(-1)
system_prompt = get_system_prompt(shell)
response = client.chat(
model=config["model"],
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": query}
],
temperature=config["temperature"],
max_tokens=config["max_tokens"])
return response
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 user's prompt (not used in this function, included for context in future use).
shell : str
The shell information to be inserted in place of the {shell} placeholder in PROMPT_FILE.
Returns
-------
str
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)
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())
return system_prompt
def chat_completion(client, query, config):
"""
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.")
sys.exit(-1)
system_prompt = get_system_prompt(config["shell"])
# Ensure query is a question
if query[-1:] != "?" and query[-1:] != ".":
query += "?"
response = client.chat(
model=config["model"],
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": query},
],
temperature=config["temperature"],
max_tokens=config["max_tokens"],
)
return response
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'))
sys.exit(-1)
"""
Checks the given response for any issues and raise an error when detected.
The function checks if the supplied text response begins with any of a set of predefined
prefixes, which indicate a problem with the response. If such a prefix is found, an error
message is printed to the console in red, and the program exits with a -1 status code.
Parameters
----------
response : str
A response text string that needs to be examined for any issues.
"""
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"))
sys.exit(-1)
def check_for_markdown(response):
if response.count("```",2):
print(colored("The proposed command contains markdown, so I did not execute the response directly: \n", 'red')+response)
sys.exit(-1)
"""
Checks for the presence of markdown formatting (specifically, code snippet markdown) in the
provided response.
This function considers the presence of markdown formatting (specifically, code block
formatting marked by ```) in the `response` as an "odd corner case". If such a case is
detected, it prints an error message in red, along with the markdown-contained response, and
then terminates the program with a -1 status code.
Parameters
----------
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
)
sys.exit(-1)
def missing_posix_display():
return 'DISPLAY' not in os.environ or not os.environ["DISPLAY"]
"""
Checks if the DISPLAY environment variable is set in a POSIX-compliant shell.
def prompt_user_for_action(config, ask_flag, response):
print("Command: " + colored(response, config["suggested_command_color"], attrs=['bold']))
modify_snippet = ""
if bool(config["modify"]) == True:
modify_snippet = " [m]odify"
copy_to_clipboard_snippet = " [c]opy to clipboard"
if os.name == "posix" and missing_posix_display():
if get_os_friendly_name() != "Darwin/macOS":
copy_to_clipboard_snippet = ""
This function runs a shell subprocess that outputs the value of the DISPLAY environment
variable. It then checks if this value is unset (i.e., equals a newline 'b'\\n'') in the
current shell environment. If the DISPLAY variable is unset, the function returns `True`
indicating a "missing" display; otherwise, it returns `False`.
if bool(config["safety"]) == True or ask_flag == True:
prompt_text = f"Execute command? [Y]es [n]o{modify_snippet}{copy_to_clipboard_snippet} ==> "
print(prompt_text, end = '')
user_input = input()
return user_input
if bool(config["safety"]) == False:
return "Y"
Returns
-------
bool
`True` if the DISPLAY environment variable is unset or empty, `False` otherwise.
"""
display = subprocess.check_output("echo $DISPLAY", shell=True)
return display == b"\n"
def prompt_user_input(config, response):
"""
Print the command proposal in blue and prompt the user for next action based on the safety
configuration.
The user is given options to execute, modify, or copy the command to clipboard if the safety
configuration is enabled (config["safety"] = True). If the safety configuration is off
(config["safety"] = False), the function automatically assumes an execution action ('Y' for
Yes). In a POSIX-compliant shell with no display available (checked using
`missing_posix_display()`), the 'copy to clipboard' option is omitted.
Parameters
----------
config : dict
The system configurations dictionary which contains a "safety" key
to determine user prompt options.
response : str
The proposed command which is to be printed and may be executed by the user.
"""
print(
"Command: "
+ colored(response, config["suggested_command_color"], attrs=["bold"])
)
if config["safety"]:
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" + modify_text + ": "
print(prompt_text, end="")
user_input = input()
else:
user_input = "Y"
return user_input
def evaluate_input(client, config, user_input, command):
"""
Evaluate the user input to either execute, modify, or copy the command.
Based on the user's response, this function takes action:
- If the user response is 'Y' or blank, the given command gets executed in the shell.
- If the user response is 'M', user can modify the command and the modified command is executed
recursively.
- If the user response is 'C', the command is copied to the clipboard.
Parameters
----------
config : dict
The system configurations dictionary. It should contain a "shell" key specifying the shell
environment.
user_input : str
The user response which determines the course of action. It can be 'Y', 'n', 'm', 'c',
or '' (empty string).
command : str
The command which is either executed, modified, or copied to clipboard.
"""
if user_input.upper() == "Y" or user_input == "":
if config["shell"] == "powershell.exe":
subprocess.run([config["shell"], "/c", command], shell=False, check=True)
else:
# Unix: /bin/bash /bin/zsh: uses -c both Ubuntu and macOS should work, others might not
subprocess.run([config["shell"], "-c", command], shell=False, check=True)
if user_input.upper() == "M":
print("Modify prompt: ", end="")
modded_query = input()
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(client, config, modded_user_input, modded_response)
if user_input.upper() == "C":
if os.name == "posix" and missing_posix_display():
return
pyperclip.copy(command)
print("Copied command to clipboard.")
def eval_user_intent_and_execute(client, config, user_input, command, shell, ask_flag):
if user_input.upper() not in ["", "Y", "C", "M"]:
print("No action taken.")
return
if user_input.upper() == "Y" or user_input == "":
if shell == "powershell.exe":
subprocess.run([shell, "/c", command], shell=False)
else:
# Unix: /bin/bash /bin/zsh: uses -c both Ubuntu and macOS should work, others might not
subprocess.run([shell, "-c", command], shell=False)
if bool(config["modify"]) and user_input.upper() == "M":
print("Modify prompt: ", end = '')
modded_query = input()
modded_response = chat_completion(client, modded_query, config, shell)
check_for_issue(modded_response)
check_for_markdown(modded_response)
user_intent = prompt_user_for_action(config, ask_flag, modded_response)
print()
eval_user_intent_and_execute(client, config, user_intent, modded_response, shell, ask_flag)
if user_input.upper() == "C":
if os.name == "posix" and missing_posix_display():
if get_os_friendly_name() != "Darwin/macOS":
return
pyperclip.copy(command)
print("Copied command to clipboard.")
def main():
init() #Enable color output on Windows using colorama
dotenv.load_dotenv()
"""
Defined starting point of source code.
"""
parser = argparse.ArgumentParser(
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"
)
args = parser.parse_args()
config = read_config()
client = AIModel.get_model_client(config)
# Load configurations and set up client
config = read_yaml_config()
client = AIModel.get_model_client(config)
set_openai_api_key(config)
# Unix based SHELL (/bin/bash, /bin/zsh), otherwise assuming it's Windows
shell = os.environ.get("SHELL", "powershell.exe")
# Process parameters
user_prompt = " ".join(args.text)
command_start_idx = 1 # Question starts at which argv index?
ask_flag = False # safety switch -a command line argument
yolo = "" # user's answer to safety switch (-a) question y/n
if args.safety:
config["safety"] = args.safety
# Parse arguments and make sure we have at least a single word
if len(sys.argv) < 2:
print_usage(config)
sys.exit(-1)
# Unix based SHELL (/bin/bash, /bin/zsh), otherwise assuming it's Windows
config["shell"] = os.environ.get("SHELL", "powershell.exe")
# Safety switch via argument -a (local override of global setting)
# Force Y/n questions before running the command
if sys.argv[1] == "-a":
ask_flag = True
command_start_idx = 2
if args.config:
print_config(config)
# To allow easy/natural use we don't require the input to be a single string.
# User can just type yolo what is my name? without having to put the question between ''
arguments = sys.argv[command_start_idx:]
user_prompt = " ".join(arguments)
# Enable color output on Windows using colorama
init()
## core prompting loop logic
result = chat_completion(client, user_prompt, config, shell)
check_for_issue(result)
check_for_markdown(result)
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(client, config, user_input, result)
users_intent = prompt_user_for_action(config, ask_flag, result)
print()
eval_user_intent_and_execute(client, config, users_intent, result, shell, ask_flag)
if __name__ == "__main__":
main()
main()
+1 -1
View File
@@ -19,4 +19,4 @@ suggested_command_color: blue # Suggested Command Color
azure_openai_api_key:
openai_api_key:
groq_api_key:
anthropic_api_key:
anthropic_api_key: