Yet Another Shell Ai Command-Line Companion
# pylint: disable=missing-function-docstring
# pylint: disable=broad-exception-caught
# pylint: disable=anomalous-backslash-in-string


import argparse
import asyncio

from rich_argparse import RawTextRichHelpFormatter

from yash_ai.console import print_terminal_command, status, Console
from yash_ai.generate import generate


parser = argparse.ArgumentParser(
    description="Welcome to Yashi - Yet Another Shell Ai Command-Line Companion, the Cat\n"
                "[bold cyan]  /\_/\  [/bold cyan]\n"
                "[bold cyan] ( o.o ) [/bold cyan]\n"
                "[bold cyan] /  |  \ [/bold cyan]\n\n"
                "Yashi is your trusty command-line companion, just simply express what \n"
                "you want your terminal to do, and Yashi will help you with it.\n\n"
                "",
    formatter_class=RawTextRichHelpFormatter,
    epilog="Examples:\n"
           "~$  [dark_orange]yashi[/dark_orange] 'freez pip libs to requirenments.txt' \n"
           "    pip freeze > requirements.txt \n"
           "~$  [dark_orange]yashi[/dark_orange] rename git branch \n"
           "    git branch -m <new-name> \n"
)
parser.add_argument('question', metavar='question', type=str, nargs='+',
                    help='The question to my shell')

async def search(prompt):
    """Search for a query text."""
    console = Console()
    with status():
        try:
            command = await generate(prompt)
            print_terminal_command(command)
        except Exception as ex:
            console.log(ex)


def main():
    args = parser.parse_args()
    query_text = ' '.join(args.question)
    asyncio.run(search(query_text))

if __name__ == '__main__':
    main()

yash_ai/__main__.py
bsnisar/yashi
import random
import rich
from rich.status import Status
from rich.text import Text
from rich.syntax import Syntax

# pylint: disable=unused-import
from rich.console import Console
# pylint: enable=unused-import

phrases = [
    "Pouncing...",
    "Chasing mice...",
    "Hunting for data...",
    "Curiosity in progress...",
    "Whiskers twitching...",
    "Tail-tapping...",
    "Napping... Just kidding!",
    "Napping... Oops, no time for that!",
    "Meow-magic happening...",
    "Catnip break... Just joking!",
    "Paws at work...",
    "Purr-fecting your request...",
    "Cat-tering to your needs...",
    "Stretching, but still working...",
    "Cat-ulating results...",
    "Climbing the data tree...",
    "Snoozing... Just a quick catnap!",
    "Cat-mand executed...",
    "Paw-sitively fetching results...",
    "On the prowl for answers..."
]

def status() -> Status:
    """
    Run Status spinner with random phrase
    """

    phrase = random.choice(phrases)
    return rich.get_console().status(phrase, spinner="dots")

def print_terminal_command(terminal_command: str):
    """
    Display a formatted terminal command in the console.

    Args:
        terminal_command (str): The terminal command to be displayed.

    Example:
        >>> print_terminal_command("ls -l")
    """
    console = rich.get_console()
    suggestion = Text("Suggestions", style="bold")
    console.print("\n", suggestion, "\n")

    code_block = Syntax(terminal_command, "shell")
    console.print(code_block)
    console.print("")

yash_ai/console.py
bsnisar/yashi
# pylint: disable=invalid-name
# pylint: disable=trailing-whitespace

import os
import textwrap

from cohere import AsyncClient


async def generate(prompt: str, api_key: str = os.environ.get("YASHI_COHERE_KEY")) -> str:
    """
    Generate a single-line terminal command based on the provided prompt.

    Args:
        prompt (str): The prompt specifying the desired terminal command.
        api_key (str, optional): The API key for Cohere. Defaults to the value 
        of the "YASHI_COHERE_KEY" environment variable.

    Returns:
        str: The generated terminal command.

    Raises:
        ValueError: If the API key is not provided or set in the environment.

    Example:
        >>> generate_terminal_command("List all files in the current directory")
        'ls'
    """
    if api_key is None:
        raise ValueError('env varialbe "YASHI_COHERE_KEY" is not set')
  
    async with AsyncClient(api_key) as co:  
        response = await co.generate(  
            model='command-nightly', 
            prompt = _generate_prompt(prompt),
            max_tokens=250,  
            temperature=0.750
        )
    return response.generations[0].text
  
def _generate_prompt(prompt: str) -> str:

    # https://docs.cohere.com/docs/prompt-engineering
    task = f'''
        Create a single-line command that can be directly run in the terminal. Do not include any other text.
        The command should do what is specified in the prompt. 
        The prompt is: {prompt}
        Reply with the single line command:
    '''.format(prompt)
    res = textwrap.dedent(task)
    return res

yash_ai/generate.py
bsnisar/yashi