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/Significant-Gravitas/Auto-GPT into plugin-support

BillSchumacher1af463b03c82
diff --cc README.md
index 001f0ffc79,9f4c6bbc63..bf05ac4b68
--- a/README.md
+++ b/README.md
@@@ -123,38 -231,41 +231,53 @@@ To use the `google_official_search` com
4. Go to the [APIs & Services Dashboard](https://console.cloud.google.com/apis/dashboard) and click "Enable APIs and Services". Search for "Custom Search API" and click on it, then click "Enable".
5. Go to the [Credentials](https://console.cloud.google.com/apis/credentials) page and click "Create Credentials". Choose "API Key".
6. Copy the API key and set it as an environment variable named `GOOGLE_API_KEY` on your machine. See setting up environment variables below.
- 7. Go to the [Custom Search Engine](https://cse.google.com/cse/all) page and click "Add".
- 8. Set up your search engine by following the prompts. You can choose to search the entire web or specific sites.
- 9. Once you've created your search engine, click on "Control Panel" and then "Basics". Copy the "Search engine ID" and set it as an environment variable named `CUSTOM_SEARCH_ENGINE_ID` on your machine. See setting up environment variables below.
+ 7. [Enable](https://console.developers.google.com/apis/api/customsearch.googleapis.com) the Custom Search API on your project. (Might need to wait few minutes to propagate)
+ 8. Go to the [Custom Search Engine](https://cse.google.com/cse/all) page and click "Add".
+ 9. Set up your search engine by following the prompts. You can choose to search the entire web or specific sites.
+ 10. Once you've created your search engine, click on "Control Panel" and then "Basics". Copy the "Search engine ID" and set it as an environment variable named `CUSTOM_SEARCH_ENGINE_ID` on your machine. See setting up environment variables below.
- *Remember that your free daily custom search quota allows only up to 100 searches. To increase this limit, you need to assign a billing account to the project to profit from up to 10K daily searches.*
+ _Remember that your free daily custom search quota allows only up to 100 searches. To increase this limit, you need to assign a billing account to the project to profit from up to 10K daily searches._
### Setting up environment variables
- For Windows Users:
- ```
+
+ For Windows Users:
+
+ ```bash
setx GOOGLE_API_KEY "YOUR_GOOGLE_API_KEY"
setx CUSTOM_SEARCH_ENGINE_ID "YOUR_CUSTOM_SEARCH_ENGINE_ID"
-
```
+
For macOS and Linux users:
- ```
+
+ ```bash
export GOOGLE_API_KEY="YOUR_GOOGLE_API_KEY"
export CUSTOM_SEARCH_ENGINE_ID="YOUR_CUSTOM_SEARCH_ENGINE_ID"
-
```
- ## Redis Setup
++## Plugins
+
- Install docker desktop.
++See https://github.com/Torantulino/Auto-GPT-Plugin-Template for the template of the plugins.
+
- Run:
- ```
++⚠️💀 WARNING 💀⚠️: Review the code of any plugin you use, this allows for any Python to be executed and do malicious things. Like stealing your API keys.
++
++Drop the repo's zipfile in the plugins folder.
++
++![Download Zip](https://raw.githubusercontent.com/BillSchumacher/Auto-GPT/master/plugin.png)
++
++If you add the plugins class name to the whitelist in the config.py you will not be prompted otherwise you'll be warned before loading the plugin.
++
+ ## Redis Setup
+ > _**CAUTION**_ \
+ This is not intended to be publicly accessible and lacks security measures. Therefore, avoid exposing Redis to the internet without a password or at all
+ 1. Install docker desktop
+ ```bash
docker run -d --name redis-stack-server -p 6379:6379 redis/redis-stack-server:latest
```
- See https://hub.docker.com/r/redis/redis-stack-server for setting a password and additional configuration.
+ > See https://hub.docker.com/r/redis/redis-stack-server for setting a password and additional configuration.
- Set the following environment variables:
- ```
+ 2. Set the following environment variables
+ > Replace **PASSWORD** in angled brackets (<>)
+ ```bash
MEMORY_BACKEND=redis
REDIS_HOST=localhost
REDIS_PORT=6379
@@@ -192,29 -315,30 +327,31 @@@ In the `.env` file set
Alternatively, you can set them from the command line (advanced):
For Windows Users:
- ```
- setx PINECONE_API_KEY "YOUR_PINECONE_API_KEY"
- setx PINECONE_ENV "Your pinecone region" # something like: us-east4-gcp
+ ```bash
+ setx PINECONE_API_KEY "<YOUR_PINECONE_API_KEY>"
+ setx PINECONE_ENV "<YOUR_PINECONE_REGION>" # e.g: "us-east4-gcp"
+ setx MEMORY_BACKEND "pinecone"
```
+
For macOS and Linux users:
- ```
- export PINECONE_API_KEY="YOUR_PINECONE_API_KEY"
- export PINECONE_ENV="Your pinecone region" # something like: us-east4-gcp
+ ```bash
+ export PINECONE_API_KEY="<YOUR_PINECONE_API_KEY>"
+ export PINECONE_ENV="<YOUR_PINECONE_REGION>" # e.g: "us-east4-gcp"
+ export MEMORY_BACKEND="pinecone"
```
- ## Plugins
+
- See https://github.com/Torantulino/Auto-GPT-Plugin-Template for the template of the plugins.
+ ## Setting Your Cache Type
- ⚠️💀 WARNING 💀⚠️: Review the code of any plugin you use, this allows for any Python to be executed and do malicious things. Like stealing your API keys.
+ By default, Auto-GPT is going to use LocalCache instead of redis or Pinecone.
- Drop the repo's zipfile in the plugins folder.
-
- ![Download Zip](https://raw.githubusercontent.com/BillSchumacher/Auto-GPT/master/plugin.png)
+ To switch to either, change the `MEMORY_BACKEND` env variable to the value that you want:
- If you add the plugins class name to the whitelist in the config.py you will not be prompted otherwise you'll be warned before loading the plugin.
+ `local` (default) uses a local JSON cache file
+ `pinecone` uses the Pinecone.io account you configured in your ENV settings
+ `redis` will use the redis cache that you configured
## View Memory Usage
diff --cc autogpt/__main__.py
index 0000000000,29ccddbfc0..8888c2060f
mode 000000,100644..100644
--- a/autogpt/__main__.py
+++ b/autogpt/__main__.py
@@@ -1,0 -1,53 +1,76 @@@
+ """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.config import Config, check_openai_api_key
+ from autogpt.logs import logger
+ from autogpt.memory import get_memory
+
+ from autogpt.prompt import construct_prompt
+
+ # 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)
++ plugins_found = load_plugins(Path(os.getcwd()) / "plugins")
++ loaded_plugins = []
++ for plugin in plugins_found:
++ if plugin.__name__ in cfg.plugins_blacklist:
++ continue
++ if plugin.__name__ in cfg.plugins_whitelist:
++ loaded_plugins.append(plugin())
++ else:
++ ack = input(
++ f"WARNNG Plugin {plugin.__name__} found. But not in the"
++ " whitelist... Load? (y/n): "
++ )
++ if ack.lower() == "y":
++ loaded_plugins.append(plugin())
++
++ if loaded_plugins:
++ print(f"\nPlugins found: {len(loaded_plugins)}\n"
++ "--------------------")
++ for plugin in loaded_plugins:
++ print(f"{plugin._name}: {plugin._version} - {plugin._description}")
++
++ cfg.set_plugins(loaded_plugins)
++
+ ai_name = ""
+ prompt = construct_prompt()
+ # print(prompt)
+ # Initialize variables
+ full_message_history = []
+ next_action_count = 0
+ # Make a constant:
+ user_input = (
+ "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(
+ f"Using memory of type:", Fore.GREEN, f"{memory.__class__.__name__}"
+ )
+ logger.typewriter_log(f"Using Browser:", Fore.GREEN, cfg.selenium_web_browser)
+ agent = Agent(
+ ai_name=ai_name,
+ memory=memory,
+ full_message_history=full_message_history,
+ next_action_count=next_action_count,
+ prompt=prompt,
+ user_input=user_input,
+ )
+ agent.start_interaction_loop()
+
+
+ if __name__ == "__main__":
+ main()
diff --cc autogpt/config/config.py
index 0000000000,b03f38ebb7..e932fe838b
mode 000000,100644..100644
--- a/autogpt/config/config.py
+++ b/autogpt/config/config.py
@@@ -1,0 -1,230 +1,238 @@@
+ """Configuration class to store the state of bools for different scripts access."""
+ import os
+ from colorama import Fore
+
+ from autogpt.config.singleton import Singleton
+
+ import openai
+ import yaml
+
+ from dotenv import load_dotenv
+
+ load_dotenv(verbose=True)
+
+
+ class Config(metaclass=Singleton):
+ """
+ Configuration class to store the state of bools for different scripts access.
+ """
+
+ def __init__(self) -> None:
+ """Initialize the Config class"""
+ self.debug_mode = False
+ self.continuous_mode = False
+ self.continuous_limit = 0
+ self.speak_mode = False
+ self.skip_reprompt = False
+
+ self.selenium_web_browser = os.getenv("USE_WEB_BROWSER", "chrome")
+ self.ai_settings_file = os.getenv("AI_SETTINGS_FILE", "ai_settings.yaml")
+ self.fast_llm_model = os.getenv("FAST_LLM_MODEL", "gpt-3.5-turbo")
+ self.smart_llm_model = os.getenv("SMART_LLM_MODEL", "gpt-4")
+ self.fast_token_limit = int(os.getenv("FAST_TOKEN_LIMIT", 4000))
+ self.smart_token_limit = int(os.getenv("SMART_TOKEN_LIMIT", 8000))
+ self.browse_chunk_max_length = int(os.getenv("BROWSE_CHUNK_MAX_LENGTH", 8192))
+ self.browse_summary_max_token = int(os.getenv("BROWSE_SUMMARY_MAX_TOKEN", 300))
+
+ self.openai_api_key = os.getenv("OPENAI_API_KEY")
+ self.temperature = float(os.getenv("TEMPERATURE", "1"))
+ self.use_azure = os.getenv("USE_AZURE") == "True"
+ self.execute_local_commands = (
+ os.getenv("EXECUTE_LOCAL_COMMANDS", "False") == "True"
+ )
+
+ if self.use_azure:
+ self.load_azure_config()
+ openai.api_type = self.openai_api_type
+ openai.api_base = self.openai_api_base
+ openai.api_version = self.openai_api_version
+
+ self.elevenlabs_api_key = os.getenv("ELEVENLABS_API_KEY")
+ self.elevenlabs_voice_1_id = os.getenv("ELEVENLABS_VOICE_1_ID")
+ self.elevenlabs_voice_2_id = os.getenv("ELEVENLABS_VOICE_2_ID")
+
+ self.use_mac_os_tts = False
+ self.use_mac_os_tts = os.getenv("USE_MAC_OS_TTS")
+
+ self.use_brian_tts = False
+ self.use_brian_tts = os.getenv("USE_BRIAN_TTS")
+
+ self.github_api_key = os.getenv("GITHUB_API_KEY")
+ self.github_username = os.getenv("GITHUB_USERNAME")
+
+ self.google_api_key = os.getenv("GOOGLE_API_KEY")
+ self.custom_search_engine_id = os.getenv("CUSTOM_SEARCH_ENGINE_ID")
+
+ self.pinecone_api_key = os.getenv("PINECONE_API_KEY")
+ self.pinecone_region = os.getenv("PINECONE_ENV")
+
+ # milvus configuration, e.g., localhost:19530.
+ self.milvus_addr = os.getenv("MILVUS_ADDR", "localhost:19530")
+ self.milvus_collection = os.getenv("MILVUS_COLLECTION", "autogpt")
+
+ self.image_provider = os.getenv("IMAGE_PROVIDER")
+ self.huggingface_api_token = os.getenv("HUGGINGFACE_API_TOKEN")
+ self.huggingface_audio_to_text_model = os.getenv(
+ "HUGGINGFACE_AUDIO_TO_TEXT_MODEL"
+ )
+
+ # User agent headers to use when browsing web
+ # Some websites might just completely deny request with an error code if
+ # no user agent was found.
+ self.user_agent = os.getenv(
+ "USER_AGENT",
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36"
+ " (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36",
+ )
+ self.redis_host = os.getenv("REDIS_HOST", "localhost")
+ self.redis_port = os.getenv("REDIS_PORT", "6379")
+ self.redis_password = os.getenv("REDIS_PASSWORD", "")
+ self.wipe_redis_on_start = os.getenv("WIPE_REDIS_ON_START", "True") == "True"
+ self.memory_index = os.getenv("MEMORY_INDEX", "auto-gpt")
+ # Note that indexes must be created on db 0 in redis, this is not configurable.
+
+ self.memory_backend = os.getenv("MEMORY_BACKEND", "local")
+ # Initialize the OpenAI API client
+ openai.api_key = self.openai_api_key
+
++ self.plugins = []
++ self.plugins_whitelist = []
++ self.plugins_blacklist = []
++
+ def get_azure_deployment_id_for_model(self, model: str) -> str:
+ """
+ Returns the relevant deployment id for the model specified.
+
+ Parameters:
+ model(str): The model to map to the deployment id.
+
+ Returns:
+ The matching deployment id if found, otherwise an empty string.
+ """
+ if model == self.fast_llm_model:
+ return self.azure_model_to_deployment_id_map[
+ "fast_llm_model_deployment_id"
+ ] # type: ignore
+ elif model == self.smart_llm_model:
+ return self.azure_model_to_deployment_id_map[
+ "smart_llm_model_deployment_id"
+ ] # type: ignore
+ elif model == "text-embedding-ada-002":
+ return self.azure_model_to_deployment_id_map[
+ "embedding_model_deployment_id"
+ ] # type: ignore
+ else:
+ return ""
+
+ AZURE_CONFIG_FILE = os.path.join(os.path.dirname(__file__), "..", "azure.yaml")
+
+ def load_azure_config(self, config_file: str = AZURE_CONFIG_FILE) -> None:
+ """
+ Loads the configuration parameters for Azure hosting from the specified file
+ path as a yaml file.
+
+ Parameters:
+ config_file(str): The path to the config yaml file. DEFAULT: "../azure.yaml"
+
+ Returns:
+ None
+ """
+ try:
+ with open(config_file) as file:
+ config_params = yaml.load(file, Loader=yaml.FullLoader)
+ except FileNotFoundError:
+ config_params = {}
+ self.openai_api_type = config_params.get("azure_api_type") or "azure"
+ self.openai_api_base = config_params.get("azure_api_base") or ""
+ self.openai_api_version = (
+ config_params.get("azure_api_version") or "2023-03-15-preview"
+ )
+ self.azure_model_to_deployment_id_map = config_params.get("azure_model_map", [])
+
+ def set_continuous_mode(self, value: bool) -> None:
+ """Set the continuous mode value."""
+ self.continuous_mode = value
+
+ def set_continuous_limit(self, value: int) -> None:
+ """Set the continuous limit value."""
+ self.continuous_limit = value
+
+ def set_speak_mode(self, value: bool) -> None:
+ """Set the speak mode value."""
+ self.speak_mode = value
+
+ def set_fast_llm_model(self, value: str) -> None:
+ """Set the fast LLM model value."""
+ self.fast_llm_model = value
+
+ def set_smart_llm_model(self, value: str) -> None:
+ """Set the smart LLM model value."""
+ self.smart_llm_model = value
+
+ def set_fast_token_limit(self, value: int) -> None:
+ """Set the fast token limit value."""
+ self.fast_token_limit = value
+
+ def set_smart_token_limit(self, value: int) -> None:
+ """Set the smart token limit value."""
+ self.smart_token_limit = value
+
+ def set_browse_chunk_max_length(self, value: int) -> None:
+ """Set the browse_website command chunk max length value."""
+ self.browse_chunk_max_length = value
+
+ def set_browse_summary_max_token(self, value: int) -> None:
+ """Set the browse_website command summary max token value."""
+ self.browse_summary_max_token = value
+
+ def set_openai_api_key(self, value: str) -> None:
+ """Set the OpenAI API key value."""
+ self.openai_api_key = value
+
+ def set_elevenlabs_api_key(self, value: str) -> None:
+ """Set the ElevenLabs API key value."""
+ self.elevenlabs_api_key = value
+
+ def set_elevenlabs_voice_1_id(self, value: str) -> None:
+ """Set the ElevenLabs Voice 1 ID value."""
+ self.elevenlabs_voice_1_id = value
+
+ def set_elevenlabs_voice_2_id(self, value: str) -> None:
+ """Set the ElevenLabs Voice 2 ID value."""
+ self.elevenlabs_voice_2_id = value
+
+ def set_google_api_key(self, value: str) -> None:
+ """Set the Google API key value."""
+ self.google_api_key = value
+
+ def set_custom_search_engine_id(self, value: str) -> None:
+ """Set the custom search engine id value."""
+ self.custom_search_engine_id = value
+
+ def set_pinecone_api_key(self, value: str) -> None:
+ """Set the Pinecone API key value."""
+ self.pinecone_api_key = value
+
+ def set_pinecone_region(self, value: str) -> None:
+ """Set the Pinecone region value."""
+ self.pinecone_region = value
+
+ def set_debug_mode(self, value: bool) -> None:
+ """Set the debug mode value."""
+ self.debug_mode = value
+
++ def set_plugins(self, value: list) -> None:
++ """Set the plugins value."""
++ self.plugins = value
++
+
+ def check_openai_api_key() -> None:
+ """Check if the OpenAI API key is set in config.py or as an environment variable."""
+ cfg = Config()
+ if not cfg.openai_api_key:
+ print(
+ Fore.RED
+ + "Please set your OpenAI API key in .env or as an environment variable."
+ )
+ print("You can get your key from https://beta.openai.com/account/api-keys")
+ exit(1)
diff --cc autogpt/llm_utils.py
index 0000000000,43739009c4..e69f83f4b3
mode 000000,100644..100644
--- a/autogpt/llm_utils.py
+++ b/autogpt/llm_utils.py
@@@ -1,0 -1,153 +1,155 @@@
+ from ast import List
+ import time
+ from typing import Dict, Optional
+
+ import openai
+ from openai.error import APIError, RateLimitError
+ from colorama import Fore
+
+ from autogpt.config import Config
+
+ CFG = Config()
+
+ openai.api_key = CFG.openai_api_key
+
+
+ def call_ai_function(
+ function: str, args: List, description: str, model: Optional[str] = None
+ ) -> str:
+ """Call an AI function
+
+ This is a magic function that can do anything with no-code. See
+ https://github.com/Torantulino/AI-Functions for more info.
+
+ Args:
+ function (str): The function to call
+ args (list): The arguments to pass to the function
+ description (str): The description of the function
+ model (str, optional): The model to use. Defaults to None.
+
+ Returns:
+ str: The response from the function
+ """
+ if model is None:
+ model = CFG.smart_llm_model
+ # For each arg, if any are None, convert to "None":
+ args = [str(arg) if arg is not None else "None" for arg in args]
+ # parse args to comma separated string
+ args = ", ".join(args)
+ messages = [
+ {
+ "role": "system",
+ "content": f"You are now the following python function: ```# {description}"
+ f"\n{function}```\n\nOnly respond with your `return` value.",
+ },
+ {"role": "user", "content": args},
+ ]
+
+ return create_chat_completion(model=model, messages=messages, temperature=0)
+
+
+ # Overly simple abstraction until we create something better
+ # simple retry mechanism when getting a rate error or a bad gateway
+ def create_chat_completion(
+ messages: List, # type: ignore
+ model: Optional[str] = None,
+ temperature: float = CFG.temperature,
+ max_tokens: Optional[int] = None,
+ ) -> str:
+ """Create a chat completion using the OpenAI API
+
+ Args:
+ messages (List[Dict[str, str]]): The messages to send to the chat completion
+ model (str, optional): The model to use. Defaults to None.
+ temperature (float, optional): The temperature to use. Defaults to 0.9.
+ max_tokens (int, optional): The max tokens to use. Defaults to None.
+
+ Returns:
+ str: The response from the chat completion
+ """
+ response = None
+ num_retries = 10
+ if CFG.debug_mode:
+ print(
+ Fore.GREEN
+ + f"Creating chat completion with model {model}, temperature {temperature},"
+ f" max_tokens {max_tokens}" + Fore.RESET
+ )
+ for attempt in range(num_retries):
+ backoff = 2 ** (attempt + 2)
+ try:
+ if CFG.use_azure:
+ response = openai.ChatCompletion.create(
+ deployment_id=CFG.get_azure_deployment_id_for_model(model),
+ model=model,
+ messages=messages,
+ temperature=temperature,
+ max_tokens=max_tokens,
+ )
+ else:
+ response = openai.ChatCompletion.create(
+ model=model,
+ messages=messages,
+ temperature=temperature,
+ max_tokens=max_tokens,
+ )
+ break
+ except RateLimitError:
+ if CFG.debug_mode:
+ print(
+ Fore.RED + "Error: ",
+ f"Reached rate limit, passing..." + Fore.RESET,
+ )
+ except APIError as e:
+ if e.http_status == 502:
+ pass
+ else:
+ raise
+ if attempt == num_retries - 1:
+ raise
+ if CFG.debug_mode:
+ print(
+ Fore.RED + "Error: ",
+ f"API Bad gateway. Waiting {backoff} seconds..." + Fore.RESET,
+ )
+ time.sleep(backoff)
+ if response is None:
+ raise RuntimeError(f"Failed to get response after {num_retries} retries")
-
- return response.choices[0].message["content"]
++ resp = response.choices[0].message["content"]
++ for plugin in CFG.plugins:
++ resp = plugin.on_response(resp)
++ return resp
+
+
+ def create_embedding_with_ada(text) -> list:
+ """Create a embedding with text-ada-002 using the OpenAI SDK"""
+ num_retries = 10
+ for attempt in range(num_retries):
+ backoff = 2 ** (attempt + 2)
+ try:
+ if CFG.use_azure:
+ return openai.Embedding.create(
+ input=[text],
+ engine=CFG.get_azure_deployment_id_for_model(
+ "text-embedding-ada-002"
+ ),
+ )["data"][0]["embedding"]
+ else:
+ return openai.Embedding.create(
+ input=[text], model="text-embedding-ada-002"
+ )["data"][0]["embedding"]
+ except RateLimitError:
+ pass
+ except APIError as e:
+ if e.http_status == 502:
+ pass
+ else:
+ raise
+ if attempt == num_retries - 1:
+ raise
+ if CFG.debug_mode:
+ print(
+ Fore.RED + "Error: ",
+ f"API Bad gateway. Waiting {backoff} seconds..." + Fore.RESET,
+ )
+ time.sleep(backoff)