Skip to content

Instantly share code, notes, and snippets.

@ahmadrosid
Last active May 12, 2024 13:35
Show Gist options
  • Save ahmadrosid/8271a015fabff6e4f8e96402f72cb1fe to your computer and use it in GitHub Desktop.
Save ahmadrosid/8271a015fabff6e4f8e96402f72cb1fe to your computer and use it in GitHub Desktop.
Create your own github copilot.

Place your prompt in the ./prompts folder.

Install python dependencies:

pip install -r requirements.txt

Usage:

python copilot.py instruction.md
import sys
from utils import read_file_to_string, write_file, parse_go_code_snippets
from llm import ask_together
from prompt_toolkit import prompt as get_input
from dotenv import load_dotenv
load_dotenv()
messages = []
def reset_messages():
prompt = read_file_to_string("./prompts/module_generator_prompt.md")
messages.append({"role": "system", "content": prompt})
def ask(question):
messages.append({"role": "user", "content": question})
response = ask_together(messages)
messages.append({"role": "assistant", "content": response})
return response
reset_messages()
args = sys.argv[1:]
if len(args) > 0:
prompt_file_path = args[0]
output = ask(read_file_to_string(prompt_file_path))
write_file("example_output_prompt.md", output.strip())
print("Output written to example_output_prompt.md")
text = read_file_to_string("example_output_prompt.md")
code_snippets = parse_go_code_snippets(text)
for snippet in code_snippets:
print(f"Create file: {snippet['file_path']}")
write_file("../" +snippet['file_path'], snippet['code'])
# print(snippet['code'])
elif len(args) == 0:
try:
while True:
user_input = get_input("Ask ai: ")
if user_input.lower() == 'exit' or user_input.lower() == 'q':
print("")
break
if user_input.lower() == 'reset':
reset_messages()
print("cleared...")
continue
if user_input == '':
continue
ask(question=user_input)
except KeyboardInterrupt:
print("")
except:
print("Unexpected error:", sys.exc_info()[0])
import os
from together import Together
together_client = Together(api_key=os.environ.get("TOGETHER_API_KEY"))
def ask_together(messages):
response = together_client.chat.completions.create(
messages=messages,
# model="meta-llama/Llama-3-8b-chat-hf",
model="mistralai/Mixtral-8x22B-Instruct-v0.1",
stream=True,
)
result = ""
for chunk in response:
result += chunk.choices[0].delta.content
print(chunk.choices[0].delta.content, end="", flush=True)
print("\n")
return result
together
prompt_toolkit
python-dotenv
pathlib
import re
from pathlib import Path
def create_file_if_not_exists(file_path):
"""
Creates a file with the given path if it doesn't already exist.
Creates the necessary directories if they don't exist.
Args:
file_path (str): The path of the file to be created.
Returns:
bool: True if the file was created, False if the file already existed.
"""
path = Path(file_path)
try:
path.parent.mkdir(parents=True, exist_ok=True)
path.touch(exist_ok=True)
return True
except Exception as e:
print(f"Error creating file or directory: {e}")
return False
def read_file_to_string(file_path):
"""
Reads the contents of a file into a string.
Args:
file_path (str): The path to the file to be read.
Returns:
str: The contents of the file as a string.
"""
try:
with open(file_path, "r") as file:
file_contents = file.read()
return file_contents
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
except Exception as e:
print(f"Error: {e}")
def write_file(file_path, data):
create_file_if_not_exists(file_path)
try:
with open(file_path, 'a') as file:
file.write(data)
except IOError:
print(f"An error occurred while writing to {file_path}.")
def parse_go_code_snippets(text):
pattern = r'\*\*(.+?):\*\*\s*```go(.*?)```'
matches = re.findall(pattern, text, re.DOTALL)
code_snippets = []
for match in matches:
file_path, code = match
code_snippets.append({
'file_path': file_path.strip(),
'code': code.strip()
})
return code_snippets
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment