Skip to content

Instantly share code, notes, and snippets.

@sam2332
Last active November 30, 2023 19:47
Show Gist options
  • Save sam2332/e9b67f2c256f2f89d4852f91b6891c3f to your computer and use it in GitHub Desktop.
Save sam2332/e9b67f2c256f2f89d4852f91b6891c3f to your computer and use it in GitHub Desktop.
This is a decorator and a function to query GPT-4
import dotenv
dotenv.load_dotenv()
import sys
import os
import openai
openai.api_key = os.environ['OPENAI_KEY']
import json
import inspect
def safe_json_parse(json_str):
try:
return json.loads(json_str)
except json.JSONDecodeError as e:
# Handle the specific JSON parsing error
print(json_str)
return json_str
class GPTFunctionCaller:
def __init__(self, model_name="gpt-4-0613", system_msg=None):
self.model_name = model_name
self.functions = {}
self.system_msg = system_msg
self.function_definitions = []
def register_function(self, func):
self.functions[func.__name__] = func
params = inspect.signature(func).parameters
param_info = {
"type": "object",
"properties": {},
"required": list(params.keys())
}
for param in params.values():
# Example of how to fill the parameter details
# You might need to adjust this depending on your specific needs
param_info["properties"][param.name] = {
"type": "string", # or other type based on your function
"description": param.name # or a more detailed description
}
self.function_definitions.append({
"name": func.__name__,
"description": func.__doc__,
"parameters": param_info
})
return func
def query(self, user_input):
messages=[]
if not self.system_msg is None:
messages.append({'role':'system','content':self.system_msg})
messages.append({"role": "user", "content": user_input})
# First GPT-4 call to potentially trigger a function call
initial_response = openai.ChatCompletion.create(
model=self.model_name,
messages=messages,
functions=self.function_definitions,
function_call="auto",
)
function_response = None
function_call = initial_response['choices'][0].get('message').get("function_call")
if function_call:
function_name = function_call["name"]
arguments_json = function_call["arguments"]
# Use the safe JSON parsing method
parsed_arguments = safe_json_parse(arguments_json)
if "error" in parsed_arguments:
return parsed_arguments["error"]
elif function_name in self.functions:
# Call the registered function with the parsed arguments
function_response = self.functions[function_name](**parsed_arguments)
if function_response:
# Second GPT-4 call with the function response added as context
final_response = openai.ChatCompletion.create(
model=self.model_name,
messages=[
{"role": "system", "content": "FUNCTION RESPONSE: "+function_response},
initial_response['choices'][0].get('message'),
{"role": "user", "content": user_input}
],
)
return final_response['choices'][0]['message']['content']
return initial_response
from pathlib import Path
# Example usage
gpt_caller = GPTFunctionCaller()
import tempfile
import subprocess
@gpt_caller.register_function
def eval_PYTHON(code):
"""EVAL PYTHON When calling this function only provide python code, it will be saved to the current folder and executed"""
with open("code.py", 'w') as temp_file:
temp_file.write(code)
try:
result = subprocess.run(["python", 'code.py'], capture_output=True, text=True, cwd = os.getcwd())
if result.stderr:
return f"Error: {result.stderr}"
return "data from python processs" + result.stdout[:500]
except Exception as e:
return f"Execution error: {e}"
import subprocess
import subprocess
import os
@gpt_caller.register_function
def eval_BASH_command(command):
"""Executes a given Bash command on users computer, loading the user's Bash profile.
Ensure that only valid and safe Bash commands are sent."""
login_shell_command = f"bash -l -c \"{command}\""
#print(login_shell_command)
try:
result = subprocess.run(login_shell_command, shell=True, capture_output=True, text=True, cwd=os.getcwd())
if result.stderr:
return f"Error: {result.stderr}"
return result.stdout[:500] # Limiting the output length for safety
except Exception as e:
return f"Execution error: {e}"
# Make a Program
response = gpt_caller.query("""
code me a pysimplegui that lets me ask questions,
it will open google to the search results page for whatever is put in the box
""")
# Make a binary
response = gpt_caller.query("""
use pyinstaller to generate a single file executable from the code.py file
""")
response
@sam2332
Copy link
Author

sam2332 commented Nov 30, 2023

DANGER ZZZZOONEEEE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment