Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

Merge branch 'master' of https://github.com/BillSchumacher/Auto-GPT into plugin-support

BillSchumacher085842d43c76
diff --cc .gitignore
index 1cac9c3c72,85111ce974..3a411a0ed4
--- a/.gitignore
+++ b/.gitignore
@@@ -157,4 -158,5 +158,7 @@@ vicuna-
# mac
.DS_Store
+openai/
++
+ # news
+ CURRENT_BULLETIN.md
diff --cc autogpt/__main__.py
index 956cf10a3d,128f9eea49..7e8bbc1a31
--- a/autogpt/__main__.py
+++ b/autogpt/__main__.py
@@@ -1,77 -1,5 +1,80 @@@
+ """Auto-GPT: A GPT powered AI Assistant"""
+ import autogpt.cli
+
+ if __name__ == "__main__":
+ autogpt.cli.main()
++
++
+"""Main script for the autogpt package."""
+import logging
+
+from colorama import Fore
+
+from autogpt.agent.agent import Agent
+from autogpt.args import parse_arguments
+from autogpt.commands.command import CommandRegistry
+from autogpt.config import Config, check_openai_api_key
+from autogpt.logs import logger
+from autogpt.memory import get_memory
+
+from autogpt.prompts.prompt import construct_main_ai_config
+from autogpt.plugins import scan_plugins
+
+
+# Load environment variables from .env file
+
+
+def main() -> None:
+ """Main function for the script"""
+ cfg = Config()
+ # TODO: fill in llm values here
+ check_openai_api_key()
+ parse_arguments()
+ logger.set_level(logging.DEBUG if cfg.debug_mode else logging.INFO)
+ cfg.set_plugins(scan_plugins(cfg, cfg.debug_mode))
+ # Create a CommandRegistry instance and scan default folder
+ command_registry = CommandRegistry()
+ command_registry.import_commands("autogpt.commands.audio_text")
+ command_registry.import_commands("autogpt.commands.evaluate_code")
+ command_registry.import_commands("autogpt.commands.execute_code")
+ command_registry.import_commands("autogpt.commands.file_operations")
+ command_registry.import_commands("autogpt.commands.git_operations")
+ command_registry.import_commands("autogpt.commands.google_search")
+ command_registry.import_commands("autogpt.commands.image_gen")
+ command_registry.import_commands("autogpt.commands.twitter")
+ command_registry.import_commands("autogpt.commands.web_selenium")
+ command_registry.import_commands("autogpt.commands.write_tests")
+ command_registry.import_commands("autogpt.app")
+ ai_name = ""
+ ai_config = construct_main_ai_config()
+ ai_config.command_registry = command_registry
+ # print(prompt)
+ # Initialize variables
+ full_message_history = []
+ next_action_count = 0
+ # Make a constant:
+ triggering_prompt = (
+ "Determine which next command to use, and respond using the"
+ " format specified above:"
+ )
+ # Initialize memory and make sure it is empty.
+ # this is particularly important for indexing and referencing pinecone memory
+ memory = get_memory(cfg, init=True)
+ logger.typewriter_log(
+ "Using memory of type:", Fore.GREEN, f"{memory.__class__.__name__}"
+ )
+ logger.typewriter_log("Using Browser:", Fore.GREEN, cfg.selenium_web_browser)
+ system_prompt = ai_config.construct_full_prompt()
+ if cfg.debug_mode:
+ logger.typewriter_log("Prompt:", Fore.GREEN, system_prompt)
+ agent = Agent(
+ ai_name=ai_name,
+ memory=memory,
+ full_message_history=full_message_history,
+ next_action_count=next_action_count,
+ command_registry=command_registry,
+ config=ai_config,
+ system_prompt=system_prompt,
+ triggering_prompt=triggering_prompt,
+ )
+ agent.start_interaction_loop()
-
-
- if __name__ == "__main__":
- main()
diff --cc autogpt/agent/agent_manager.py
index 9f123eaace,898767a485..a35da3c2f3
--- a/autogpt/agent/agent_manager.py
+++ b/autogpt/agent/agent_manager.py
@@@ -1,10 -1,10 +1,13 @@@
"""Agent manager for managing GPT agents"""
from __future__ import annotations
+from typing import List
+ from typing import Union
+
-from autogpt.config.config import Singleton
++
+from autogpt.config.config import Config, Singleton
from autogpt.llm_utils import create_chat_completion
+from autogpt.types.openai import Message
class AgentManager(metaclass=Singleton):
diff --cc autogpt/app.py
index 38c49e4261,381f5a2aa0..38e9cb5807
--- a/autogpt/app.py
+++ b/autogpt/app.py
@@@ -1,11 -1,15 +1,16 @@@
""" Command and Control """
import json
- from typing import List, NoReturn, Union, Dict
+ from typing import Dict, List, NoReturn, Union
+
from autogpt.agent.agent_manager import AgentManager
from autogpt.commands.audio_text import read_audio_from_file
+from autogpt.commands.command import CommandRegistry, command
from autogpt.commands.evaluate_code import evaluate_code
- from autogpt.commands.execute_code import execute_python_file, execute_shell
+ from autogpt.commands.execute_code import (
+ execute_python_file,
+ execute_shell,
+ execute_shell_popen,
+ )
from autogpt.commands.file_operations import (
append_to_file,
delete_file,
@@@ -118,21 -116,44 +124,20 @@@ def execute_command
arguments (dict): The arguments for the command
Returns:
- str: The result of the command"""
- memory = get_memory(CFG)
-
+ str: The result of the command
+ """
try:
+ cmd = command_registry.commands.get(command_name)
+
+ # If the command is found, call it with the provided arguments
+ if cmd:
+ return cmd(**arguments)
+
+ # TODO: Remove commands below after they are moved to the command registry.
- command_name = map_command_synonyms(command_name)
+ command_name = map_command_synonyms(command_name.lower())
- if command_name == "google":
- # Check if the Google API key is set and use the official search method
- # If the API key is not set or has only whitespaces, use the unofficial
- # search method
- key = CFG.google_api_key
- if key and key.strip() and key != "your-google-api-key":
- google_result = google_official_search(arguments["input"])
- return google_result
- else:
- google_result = google_search(arguments["input"])
-
- # google_result can be a list or a string depending on the search results
- if isinstance(google_result, list):
- safe_message = [
- google_result_single.encode("utf-8", "ignore")
- for google_result_single in google_result
- ]
- else:
- safe_message = google_result.encode("utf-8", "ignore")
- return safe_message.decode("utf-8")
- elif command_name == "memory_add":
- memory = get_memory(CFG)
+ if command_name == "memory_add":
return memory.add(arguments["string"])
- elif command_name == "start_agent":
- return start_agent(
- arguments["name"], arguments["task"], arguments["prompt"]
- )
- elif command_name == "message_agent":
- return message_agent(arguments["key"], arguments["message"])
- elif command_name == "list_agents":
- return list_agents()
- elif command_name == "delete_agent":
- return delete_agent(arguments["key"])
elif command_name == "get_text_summary":
return get_text_summary(arguments["url"], arguments["question"])
elif command_name == "get_hyperlinks":
@@@ -141,10 -176,43 +146,18 @@@
if not CFG.allow_downloads:
return "Error: You do not have user authorization to download files locally."
return download_file(arguments["url"], arguments["file"])
-
- elif command_name == "browse_website":
- return browse_website(arguments["url"], arguments["question"])
- # TODO: Change these to take in a file rather than pasted code, if
- # non-file is given, return instructions "Input should be a python
- # filepath, write your code to file and try again"
- elif command_name == "evaluate_code":
- return evaluate_code(arguments["code"])
- elif command_name == "improve_code":
- return improve_code(arguments["suggestions"], arguments["code"])
- elif command_name == "write_tests":
- return write_tests(arguments["code"], arguments.get("focus"))
- elif command_name == "execute_python_file": # Add this command
- return execute_python_file(arguments["file"])
- elif command_name == "execute_shell":
- if CFG.execute_local_commands:
- return execute_shell(arguments["command_line"])
- else:
- return (
- "You are not allowed to run local shell commands. To execute"
- " shell commands, EXECUTE_LOCAL_COMMANDS must be set to 'True' "
- "in your config. Do not attempt to bypass the restriction."
- )
+ elif command_name == "execute_shell_popen":
+ if CFG.execute_local_commands:
+ return execute_shell_popen(arguments["command_line"])
+ else:
+ return (
+ "You are not allowed to run local shell commands. To execute"
+ " shell commands, EXECUTE_LOCAL_COMMANDS must be set to 'True' "
+ "in your config. Do not attempt to bypass the restriction."
+ )
- elif command_name == "read_audio_from_file":
- return read_audio_from_file(arguments["file"])
- elif command_name == "generate_image":
- return generate_image(arguments["prompt"])
- elif command_name == "send_tweet":
- return send_tweet(arguments["text"])
+ # TODO: Change these to take in a file rather than pasted code, if
+ # non-file is given, return instructions "Input should be a python
+ # filepath, write your code to file and try again
elif command_name == "do_nothing":
return "No action performed."
elif command_name == "task_complete":
diff --cc autogpt/commands/execute_code.py
index b67707279a,95ba612264..2ea14d8368
--- a/autogpt/commands/execute_code.py
+++ b/autogpt/commands/execute_code.py
@@@ -5,15 -5,10 +5,15 @@@ import subproces
import docker
from docker.errors import ImageNotFound
+from autogpt.commands.command import command
+from autogpt.config import Config
from autogpt.workspace import WORKSPACE_PATH, path_in_workspace
+CFG = Config()
+
+@command("execute_python_file", "Execute Python File", '"file": "<file>"')
- def execute_python_file(file: str):
+ def execute_python_file(file: str) -> str:
"""Execute a Python file in a Docker container and return the output
Args:
diff --cc autogpt/commands/file_operations.py
index 9011dc3b2e,72b02b5d31..5bb45179d3
--- a/autogpt/commands/file_operations.py
+++ b/autogpt/commands/file_operations.py
@@@ -5,17 -5,15 +5,18 @@@ import o
import os.path
from pathlib import Path
from typing import Generator, List
+
import requests
- from requests.adapters import HTTPAdapter
- from requests.adapters import Retry
- from colorama import Fore, Back
+ from colorama import Back, Fore
+ from requests.adapters import HTTPAdapter, Retry
+
from autogpt.spinner import Spinner
from autogpt.utils import readable_file_size
+
+from autogpt.commands.command import command
from autogpt.workspace import WORKSPACE_PATH, path_in_workspace
+
LOG_FILE = "file_logger.txt"
LOG_FILE_PATH = WORKSPACE_PATH / LOG_FILE
diff --cc autogpt/commands/git_operations.py
index 480d3a6ef2,028f3b8da4..0536152bb8
--- a/autogpt/commands/git_operations.py
+++ b/autogpt/commands/git_operations.py
@@@ -8,15 -7,8 +8,15 @@@ from autogpt.workspace import path_in_w
CFG = Config()
+@command(
+ "clone_repository",
+ "Clone Repositoryy",
+ '"repository_url": "<url>", "clone_path": "<directory>"',
+ CFG.github_username and CFG.github_api_key,
+ "Configure github_username and github_api_key.",
+)
def clone_repository(repo_url: str, clone_path: str) -> str:
- """Clone a github repository locally
+ """Clone a GitHub repository locally
Args:
repo_url (str): The URL of the repository to clone
diff --cc autogpt/commands/google_search.py
index f549ae8f6e,7d38ce7568..85eeae65bb
--- a/autogpt/commands/google_search.py
+++ b/autogpt/commands/google_search.py
@@@ -11,9 -10,8 +11,9 @@@ from autogpt.config import Confi
CFG = Config()
+@command("google", "Google Search", '"query": "<search>"', not CFG.google_api_key)
def google_search(query: str, num_results: int = 8) -> str:
- """Return the results of a google search
+ """Return the results of a Google search
Args:
query (str): The search query.
@@@ -33,19 -31,11 +33,19 @@@
for j in results:
search_results.append(j)
- return json.dumps(search_results, ensure_ascii=False, indent=4)
+ results = json.dumps(search_results, ensure_ascii=False, indent=4)
+ return safe_google_results(results)
+@command(
+ "google",
+ "Google Search",
+ '"query": "<search>"',
+ bool(CFG.google_api_key),
+ "Configure google_api_key.",
+)
def google_official_search(query: str, num_results: int = 8) -> str | list[str]:
- """Return the results of a google search using the official Google API
+ """Return the results of a Google search using the official Google API
Args:
query (str): The search query.
diff --cc autogpt/llm_utils.py
index a6d87c300c,821820ffab..48561da94a
--- a/autogpt/llm_utils.py
+++ b/autogpt/llm_utils.py
@@@ -1,14 -1,14 +1,15 @@@
from __future__ import annotations
import time
-from ast import List
+from typing import List, Optional
import openai
- from colorama import Fore
+ from colorama import Fore, Style
from openai.error import APIError, RateLimitError
from autogpt.config import Config
+from autogpt.types.openai import Message
+ from autogpt.logs import logger
CFG = Config()
@@@ -69,25 -69,15 +70,26 @@@ def create_chat_completion
Returns:
str: The response from the chat completion
"""
- response = None
num_retries = 10
+ warned_user = False
if CFG.debug_mode:
print(
- Fore.GREEN
- + f"Creating chat completion with model {model}, temperature {temperature},"
- f" max_tokens {max_tokens}" + Fore.RESET
+ f"{Fore.GREEN}Creating chat completion with model {model}, temperature {temperature}, max_tokens {max_tokens}{Fore.RESET}"
)
+ for plugin in CFG.plugins:
+ if plugin.can_handle_chat_completion(
+ messages=messages,
+ model=model,
+ temperature=temperature,
+ max_tokens=max_tokens,
+ ):
+ return plugin.handle_chat_completion(
+ messages=messages,
+ model=model,
+ temperature=temperature,
+ max_tokens=max_tokens,
+ )
+ response = None
for attempt in range(num_retries):
backoff = 2 ** (attempt + 2)
try:
@@@ -110,10 -100,19 +112,16 @@@
except RateLimitError:
if CFG.debug_mode:
print(
- Fore.RED + "Error: ",
- f"Reached rate limit, passing..." + Fore.RESET,
+ f"{Fore.RED}Error: ", f"Reached rate limit, passing...{Fore.RESET}"
)
+ if not warned_user:
+ logger.double_check(
+ f"Please double check that you have setup a {Fore.CYAN + Style.BRIGHT}PAID{Style.RESET_ALL} OpenAI API Account. "
+ + f"You can read more here: {Fore.CYAN}https://github.com/Significant-Gravitas/Auto-GPT#openai-api-keys-configuration{Fore.RESET}"
+ )
+ warned_user = True
except APIError as e:
- if e.http_status == 502:
- pass
- else:
+ if e.http_status != 502:
raise
if attempt == num_retries - 1:
raise
@@@ -124,13 -123,19 +132,23 @@@
)
time.sleep(backoff)
if response is None:
- raise RuntimeError(f"Failed to get response after {num_retries} retries")
+ logger.typewriter_log(
+ "FAILED TO GET RESPONSE FROM OPENAI",
+ Fore.RED,
+ "Auto-GPT has failed to get a response from OpenAI's services. "
+ + f"Try running Auto-GPT again, and if the problem the persists try running it with `{Fore.CYAN}--debug{Fore.RESET}`.",
+ )
+ logger.double_check()
+ if CFG.debug_mode:
+ raise RuntimeError(f"Failed to get response after {num_retries} retries")
+ else:
+ quit(1)
-
- return response.choices[0].message["content"]
+ resp = response.choices[0].message["content"]
+ for plugin in CFG.plugins:
+ if not plugin.can_handle_on_response():
+ continue
+ resp = plugin.on_response(resp)
+ return resp
def create_embedding_with_ada(text) -> list:
diff --cc requirements.txt
index 9940df231c,b4245323e9..77924609ba
--- a/requirements.txt
+++ b/requirements.txt
@@@ -29,9 -30,9 +30,11 @@@ blac
sourcery
isort
gitpython==3.1.31
+abstract-singleton
+auto-gpt-plugin-template
+ # Items below this point will not be included in the Docker Image
+
# Testing dependencies
pytest
asynctest