Skip to content

Commit

Permalink
added general question mode
Browse files Browse the repository at this point in the history
  • Loading branch information
JoelKronander committed Sep 21, 2023
1 parent 00611ef commit 50c1f6c
Show file tree
Hide file tree
Showing 6 changed files with 58 additions and 35 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ terminal-copilot will then display the correct syntax for the command you need:
```find . -name "*.txt"```
With options to execute, copy, or explain the proposed terminal command.

You can also use the copilot to ask a general question to gpt4 from your command line using the -q option
```copilot -q "What is the best drink for late night coding?"```

### Installation
To use terminal-copilot, you must first install it on your system. The easiest way to do this is using pip:
```pip install terminal-copilot```
Expand All @@ -26,6 +29,9 @@ Here are some examples of how you can use terminal-copilot:
3. `copilot install the openai package for python`
4. `copilot clean up my docker images`

or you can ask a general question to gpt4 from your command line using the -q option
`copilot -q Why is 42 the meaning of life`
(note that question marks are not supported atm..)

### Arguments
Terminal-copilot can be called with optional command line arguments:
Expand Down
52 changes: 20 additions & 32 deletions copilot/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from copilot.parse_os import parse_operating_system, OperatingSystem
from copilot.parse_args import parse_terminal_copilot_args
from copilot.messages_builder import Context, build_conversation

from copilot.question import ask_question

def is_unix_system():
return platform.system().lower().startswith("lin") or platform.system().lower().startswith("dar")
Expand All @@ -31,6 +31,8 @@ def main():
if args.verbose:
print("Verbose mode enabled")

setup_openai_key()

# TODO to get more terminal context to work with..
# TODO save history of previous user questions and answers

Expand All @@ -49,6 +51,8 @@ def main():
current_dir = os.getcwd()
directory_list = os.listdir()

# if args.question:
# args.model = 'gpt-4'

context = Context(
shell=shell,
Expand All @@ -61,44 +65,18 @@ def main():
model=args.model,
)

prompt = f"""
You are an AI Terminal Copilot. Your job is to help users find the right terminal command in a {shell} on {operating_system}.
The user is asking for the following command:
'{" ".join(args.command)}'
The user is currently in the following directory:
{current_dir}
That directory contains the following files:
[{", ".join(directory_list)[:300]}]
{history.get_history() if args.history and is_unix_system() else ""}
The user has several environment variables set, some of which are:
{environs}
{git_info() if args.git else ""}
"""
if (
args.alias
and is_unix_system()
):
prompt += f"""
The user has the following aliases set:
{subprocess.run(["alias"], capture_output=True, shell=True).stdout.decode("utf-8")}
"""
# check if the -q flag is set for general questions
if args.question:
# In this case just send the question to GPT-4 and print the response
ask_question(context, args.command)
sys.exit(0)

conversation = build_conversation(context)

if args.verbose:
print("Sent this conversation to OpenAI:")
print(conversation)

openai.api_key = os.environ.get("OPENAI_API_KEY")
if openai.api_key is None:
print("To use copilot please set the OPENAI_API_KEY environment variable")
print("You can get an API key from https://beta.openai.com/account/api-keys")
print("To set the environment variable, run:")
print("export OPENAI_API_KEY=<your key>")
sys.exit(1)

if args.json:
cmds = request_cmds(conversation, n=int(args.count) if args.json and args.count else 1)
print(json.dumps({
Expand All @@ -110,6 +88,16 @@ def main():
show_command_options(conversation, cmds, args)


def setup_openai_key():
openai.api_key = os.environ.get("OPENAI_API_KEY")
if openai.api_key is None:
print("To use copilot please set the OPENAI_API_KEY environment variable")
print("You can get an API key from https://beta.openai.com/account/api-keys")
print("To set the environment variable, run:")
print("export OPENAI_API_KEY=<your key>")
sys.exit(1)


def fetch_and_print_cmd(conversation, args):
if args.no_stream:
cmds = request_cmds(conversation, n=int(args.count) if args.json and args.count else 1)[0]
Expand Down
6 changes: 4 additions & 2 deletions copilot/messages_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,12 @@ def system_messages(context: Context) -> list:
return messages


def build_conversation(context: Context) -> Conversation:
def build_conversation(context: Context, usermessage: str) -> Conversation:
messages = []
messages.extend(system_messages(context))
messages.append({"role": "user", "content": user_message(context)})
if not usermessage:
usermessage = user_message(context)
messages.append({"role": "user", "content": usermessage})
return Conversation(
messages=messages,
model=context.model
Expand Down
3 changes: 3 additions & 0 deletions copilot/parse_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,8 @@ def parse_terminal_copilot_args():
default=False,
help="Disable streaming the command into the terminal (by default, streaming is enabled)."
)
parser.add_argument(
"-q", "--question", action="store_true", default=False, help="Ask a general question to GPT-4."
)
args = parser.parse_args()
return args
24 changes: 24 additions & 0 deletions copilot/question.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# for asking general questions directly to gpt4

from typing import List

from copilot.context import Context
from copilot.conversation import Conversation
from copilot.open_ai_adapter import stream_cmd_into_terminal, request_cmds


def ask_question(context: Context, question: List[str]) -> None:
prompt = " ".join(question)

messages = []
messages.append({"role": "system", "content": "You are an AI Copilot operating in a terminal. You are a general assistant to the user."})
messages.append({"role": "user", "content": prompt})
conversation = Conversation(
messages=messages,
model=context.model
)

response = stream_cmd_into_terminal(conversation)
print(response)


2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

setup(
name ='terminal-copilot',
version ='1.3.3',
version ='1.4.0',
author ='Methexis',
author_email ='joelkronander@gmail.com',
url ='https://github.com/Methexis-Inc/terminal-copilot',
Expand Down

0 comments on commit 50c1f6c

Please sign in to comment.