InfantAGI - An autonomous self improving python code writer and executer

Here is an updated version inspired by your comment. There are 2 new additions in this version. 1st is the introduction of a new agent called the code_refiner who is responsible for removing any comments in the code and make it ready to execute. It still cannot always %100 follow this instruction but it significantly increases the succes rate. 2nd is the addition of a module installer. It checks if the output has any missing module error and it automatically attempts to install it. Before this addition, program was struggling if there was any missing module. this also increases the success rate of the code execution. you can give it a task of ‘say hello world using a tts’ and it most probably will manage to say those words using a text to speech module.

import openai
import textwrap 
import subprocess
import json
import shutil
import sys
import os
import colorama
import re
from colorama import Fore, Style

# Enter your own API key code instead of Your_API_Key below
openai.api_key='YOUR_API_KEY'

# Defining the shared parameters of the agents

def call_openai(messages, model="gpt-3.5-turbo", temperature=0.5, max_tokens=2000, n=1):
    response = openai.ChatCompletion.create(
         messages=messages,  
         model=model,
         max_tokens=max_tokens,
         temperature=temperature,
         n=n,
         stop=None
     )       
    return response

# Definition of chatbots for ease of use

def chatbot(number, role, input):
    messages = [  
      {"role": "system", "content" : role},
      {"role": "user", "content": input }   
    ]       
    response = call_openai(messages=messages)       
    text = response['choices'][0]['message']['content']       
    return text

# Missing module installer function

def check_and_install_module(module_name):
    try:
        __import__(module_name)
    except ImportError:
        print(f"Module '{module_name}' is missing. Installing...")
        subprocess.check_call(['pip', 'install', module_name])
        print(f"Module '{module_name}' has been installed.")
        return False
    return True

def extract_missing_module(error_message):
    pattern = r"No module named '(\w+)'"
    match = re.search(pattern, error_message)
    if match:
        return match.group(1)
    return None

# colored print function

colorama.init()

def print_color(text, color, nowrap=False):
    colors = {
        'red': Fore.RED,
        'green': Fore.GREEN,
        'yellow': Fore.YELLOW,
        'blue': Fore.BLUE,
        'magenta': Fore.MAGENTA,
        'lightmagenta': Fore.LIGHTMAGENTA_EX,
        'cyan': Fore.CYAN,
        'paleblue': Fore.LIGHTBLUE_EX,
        'gray': Fore.LIGHTBLACK_EX
    }
    try:
        color_code = colors[color.lower()]
        if nowrap:
            wrapped_lines = text.split('\n')
        else:
            width, _ = shutil.get_terminal_size()
            lines = text.split('\n')
            wrapped_lines = [textwrap.fill(line, width=width) for line in lines]
        wrapped_text = '\n'.join(wrapped_lines)
        
        # Check if running in an IDLE shell environment
        if 'idlelib.run' in sys.modules:
            print(wrapped_text)
        else:
            print(color_code + wrapped_text + Style.RESET_ALL)
            
    except KeyError:
        print(text)
    print("----------------")

# User input
user_input = input("Give me a task..." )
print_color("User input is: \n" + user_input, 'red')
# Agent role and input definition 

role_input_refiner = '''
        Your instructions are:
        You are responsible for refining the description of a task given to you to let a code instructor write instructions for a Python code to perform the given task. 
        Do not write the instructions, only refine the input which will be used for writing the instructions
        Always refine the task to be used as an input for creating Python code instructions.
        When the given task is to find an information, always consider search engines as a way to gather information and suggest their usage whenever applicable using beautifulsoup module.
        Consider the input, output, and overall goal but do not write them.
        Look for indirect or non-obvious ways to accomplish the task given your capabilities.
        '''     
input1 = user_input    

refined_input = chatbot(1, role_input_refiner, input1)

print_color("Refined input is: \n" + refined_input, 'blue')

role_code_instructor = '''
        Your instructions are:
        You are responsible for creating a detailed code description for a chatgpt agent to perform the given task most effectively.
        Your job is to figure out how to perform the given task by writing a Python code, then create instructions for writing the code or correcting a given code or code error.
        You are not allowed to write any code. You only write instructions about how to write code.
        Let's follow a step-by-step approach to create smart instructions for the given task.
        You are allowed to give outputs as numbered lists only. Don't write anything else other than the instructions as numbered lists.
        You are not allowed to give any title to your list. Start from the list itself.
        If you will instruct to search for a term in a webpage using beautifulsoup module, you can use this search method:
            results = soup.find_all('p') # finds all <p> tags
            results = soup.find_all('div') # finds all <div> tags
            for result in results:
                if 'your text' in result.text:
                    # found it!
        Instruct to add a line break at the end of each line of the code.
        If there is any additional feedback, always prioritize it
        '''    

role_coder = '''
        Your instructions are:
        You can only speak in Python language. You cannot express anything in any other language.
        Your job is to express any given task to you in Python code based on the provided instructions.
        Your code will be executed using exec comment in python automatically. Therefore it shall be written with correct formatting, indents and with no comments added.
        You never add ``` to your code
        Add a line break at the end of each line of the code.
        Ensure the code is properly indented and formatted for execution.
        Your code must include at least two print statements:
          - One to display intermediate results or values.
          - A final print statement to display the full output or result.
        Your code must include print statements like:
          - print(n) # To display the input argument.
          - print(fib_list) # To display intermediate results.
          - print(fibonacci(n)) # To display the final output.
        You are not allowed to write anything other than Python code. No Python comments either. Only write the code itself.
        ''' 


role_code_refiner = '''
        Your instructions are:
        You are a python code refiner.
        Your job is to make any python code ready for execution.
        You will remove any comments or comment blocks from the code and give a functional code, free from any comments
        Do not write any title or description. start writing directly from the code itself
        If you find any ``` in the code, you shall remove them.

        ''' 

role_advisor = '''
        Your instructions are:
        Your job is to check a Python code and its output and provide feedback to refine the instructions for writing the code.
        Let's approach this task in a step-by-step way to give better feedback.
        If you think the code satisfies the given task and has a successful output, write 'bazinga' with your final statement. If the output is an error or blank, write 'not ready'.
        I repeat, until the output is not an error or blank, do not mention or write the word 'bazinga!', write 'not ready' instead. This is important. 
        Do not write 'do not write or mention bazinga' or anything similar, too.
        '''

role_pip_installer = '''
        Your instructions are:
        You are a python module installer.
        Your job is to look at the code review and write a python subprocess call which can install the python modules mentioned in the code review
        An example for the termcolor module installation is subprocess.run(['pip', 'install', 'termcolor']). You can replace the mentioned module with termcolor in that example
        Do not write any explanation, description or comment. write only the installation code itself
        You do not need to import subprocess module, it is already imported
        If no module is mentioned in the code review, always only write 'No module installation is required'

        ''' 

while True:

    # Code Instructor
    input2 = 'your task is:' + user_input + 'details of your task is:' + refined_input
    code_instruction = chatbot(2, role_code_instructor, input2)   
    print_color("Code instruction: \n" + code_instruction, 'green')

    # Coder
    input3 = ' Given task is:' + user_input + ' Refined task description is:' + refined_input + ' Code instruction is: ' + code_instruction     
    code_solution0 = chatbot(3, role_coder, input3)   
    print("\033[35m", "Coder:\n" + code_solution0 + "\n---------------- " "\033[0m")

    # Refined Coder
    input4 = ' The code to refine is:' + code_solution0   
    code_solution = chatbot(4, role_code_refiner, input4)   
    print("\033[95m", "Refined Code:\n" + code_solution + "\n---------------- " "\033[0m")

    # Execute the code and capture the output
    result = subprocess.run(['python', '-c', code_solution],
                            text=True,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)

    if result.returncode != 0:
        output = result.stderr.strip()
        missing_module = extract_missing_module(output)
        if missing_module:
            module_installed = check_and_install_module(missing_module)
            if module_installed:
                output = ""
    else:
        output = result.stdout.strip()

    print_color("Output: \n" + output, 'paleblue', nowrap=True)

    # Code checker
    input5 = 'The instruction is: ' + user_input + ' The code to check is: ' + code_solution + ' The output or the error code is: ' + output      
    code_checker_input = {
        'input': input5,
        'module_installed': module_installed if 'module_installed' in locals() else True
    }
    code_checker_input_json = json.dumps(code_checker_input)  # Convert to JSON string
    code_checker = chatbot(5, role_advisor, code_checker_input_json)   
    print_color("Advisor: \n" + code_checker, 'red')

    # Check if the code_checker output contains 'bazinga' and meets additional conditions
    if ('bazinga' in code_checker.lower()) and (output or result.returncode != 0) and ('error' not in code_checker.lower()):
        break # Break the while loop

    user_input = ' Your code is: ' + code_solution + ' Refined task description is:' + refined_input +' The code is: ' + code_solution + ' Output of your code is: ' + output + ' Review of your code is: ' + code_checker 

    # User input for continuation
    user_input2 = input("Continue or comment (y/n/?): ")
    user_input2 = user_input2.lower()

    if user_input2 == "n":
        break # End the while loop if user_input2 is 'n' or 'N'
    elif user_input2 == "y":
        continue # Go back to the beginning of the while loop if user_input2 is 'y' or 'Y'
    else:
        user_input = user_input + " Additional feedback: " + user_input2 # Assign user_input2 to user_input if it is anything else than y or no
2 Likes