soulwax commited on
Commit
a9612b3
2 Parent(s): 923696f 375afca

Merge branch 'main' of https://huggingface.co/spaces/soulwax89/bluesix

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +1 -1
  2. README.md +479 -2
  3. autogpt/agent/__init__.py +4 -0
  4. autogpt/agent/agent.py +183 -0
  5. autogpt/agent/agent_manager.py +100 -0
  6. autogpt/app.py +298 -0
  7. autogpt/args.py +137 -0
  8. autogpt/commands/__init__.py +0 -0
  9. autogpt/commands/evaluate_code.py +25 -0
  10. autogpt/commands/execute_code.py +125 -0
  11. autogpt/commands/file_operations.py +196 -0
  12. autogpt/commands/git_operations.py +20 -0
  13. autogpt/commands/google_search.py +86 -0
  14. autogpt/commands/image_gen.py +99 -0
  15. autogpt/commands/improve_code.py +28 -0
  16. autogpt/commands/times.py +10 -0
  17. autogpt/commands/web_playwright.py +78 -0
  18. autogpt/commands/web_requests.py +170 -0
  19. autogpt/commands/web_selenium.py +141 -0
  20. autogpt/commands/write_tests.py +29 -0
  21. autogpt/config/__init__.py +14 -0
  22. autogpt/config/ai_config.py +118 -0
  23. autogpt/config/config.py +227 -0
  24. autogpt/config/singleton.py +24 -0
  25. autogpt/json_fixes/__init__.py +0 -0
  26. autogpt/json_fixes/auto_fix.py +53 -0
  27. autogpt/json_fixes/bracket_termination.py +73 -0
  28. autogpt/json_fixes/escaping.py +33 -0
  29. autogpt/json_fixes/missing_quotes.py +27 -0
  30. autogpt/json_fixes/parsing.py +143 -0
  31. autogpt/json_fixes/utilities.py +20 -0
  32. autogpt/logs.py +288 -0
  33. autogpt/memory/milvus.py +121 -0
  34. autogpt/permanent_memory/__init__.py +0 -0
  35. autogpt/permanent_memory/sqlite3_store.py +123 -0
  36. autogpt/processing/__init__.py +0 -0
  37. autogpt/processing/html.py +32 -0
  38. autogpt/processing/text.py +132 -0
  39. autogpt/setup.py +69 -0
  40. autogpt/speech/__init__.py +4 -0
  41. autogpt/speech/base.py +50 -0
  42. autogpt/speech/brian.py +39 -0
  43. autogpt/speech/eleven_labs.py +71 -0
  44. autogpt/speech/gtts.py +21 -0
  45. autogpt/speech/macos_tts.py +21 -0
  46. autogpt/speech/say.py +42 -0
  47. docs/imgs/openai-api-key-billing-paid-account.png +0 -0
  48. requirements-docker.txt +25 -0
  49. run.bat +8 -0
  50. run_continuous.bat +3 -0
.gitignore CHANGED
@@ -151,4 +151,4 @@ dmypy.json
151
  # Pyre type checker
152
  .pyre/
153
  llama-*
154
- vicuna-*
 
151
  # Pyre type checker
152
  .pyre/
153
  llama-*
154
+ vicuna-*
README.md CHANGED
@@ -5,7 +5,7 @@ colorTo: indigo
5
  sdk: streamlit
6
  python_version: 3.9
7
  sdk_version: 1.0.0
8
- app_file: app.py
9
  app_port: 7860
10
  fullWidth: false
11
  models:
@@ -19,4 +19,481 @@ tags:
19
  pinned: true
20
  ---
21
 
22
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  sdk: streamlit
6
  python_version: 3.9
7
  sdk_version: 1.0.0
8
+ app_file: main.py
9
  app_port: 7860
10
  fullWidth: false
11
  models:
 
19
  pinned: true
20
  ---
21
 
22
+ > This information takes precedence over any other information provided and should be followed accordingly.
23
+
24
+ Our workflow has been improved, but please note that `master` branch may often be in a **broken** state.
25
+ Please download the latest `stable` release from here: https://github.com/Torantulino/Auto-GPT/releases/latest.
26
+
27
+ ![GitHub Repo stars](https://img.shields.io/github/stars/Torantulino/auto-gpt?style=social)
28
+ [![Twitter Follow](https://img.shields.io/twitter/follow/siggravitas?style=social)](https://twitter.com/SigGravitas)
29
+ [![Discord Follow](https://dcbadge.vercel.app/api/server/autogpt?style=flat)](https://discord.gg/autogpt)
30
+ [![Unit Tests](https://github.com/Torantulino/Auto-GPT/actions/workflows/ci.yml/badge.svg)](https://github.com/Torantulino/Auto-GPT/actions/workflows/ci.yml)
31
+
32
+ Auto-GPT is an experimental open-source application showcasing the capabilities of the GPT-4 language model. This program, driven by GPT-4, chains together LLM "thoughts", to autonomously achieve whatever goal you set. As one of the first examples of GPT-4 running fully autonomously, Auto-GPT pushes the boundaries of what is possible with AI.
33
+
34
+ ### Demo (30/03/2023):
35
+
36
+ https://user-images.githubusercontent.com/22963551/228855501-2f5777cf-755b-4407-a643-c7299e5b6419.mp4
37
+
38
+ <h2 align="center"> 💖 Help Fund Auto-GPT's Development 💖</h2>
39
+ <p align="center">
40
+ If you can spare a coffee, you can help to cover the API costs of developing Auto-GPT and help push the boundaries of fully autonomous AI!
41
+ A full day of development can easily cost as much as $20 in API costs, which for a free project is quite limiting.
42
+ Your support is greatly appreciated
43
+ </p>
44
+
45
+ <p align="center">
46
+ Development of this free, open-source project is made possible by all the <a href="https://github.com/Torantulino/Auto-GPT/graphs/contributors">contributors</a> and <a href="https://github.com/sponsors/Torantulino">sponsors</a>. If you'd like to sponsor this project and have your avatar or company logo appear below <a href="https://github.com/sponsors/Torantulino">click here</a>.
47
+
48
+ <h3 align="center">Individual Sponsors</h3>
49
+ <p align="center">
50
+ <a href="https://github.com/robinicus"><img src="https://github.com/robinicus.png" width="50px" alt="robinicus" /></a>&nbsp;&nbsp;<a href="https://github.com/prompthero"><img src="https://github.com/prompthero.png" width="50px" alt="prompthero" /></a>&nbsp;&nbsp;<a href="https://github.com/crizzler"><img src="https://github.com/crizzler.png" width="50px" alt="crizzler" /></a>&nbsp;&nbsp;<a href="https://github.com/tob-le-rone"><img src="https://github.com/tob-le-rone.png" width="50px" alt="tob-le-rone" /></a>&nbsp;&nbsp;<a href="https://github.com/FSTatSBS"><img src="https://github.com/FSTatSBS.png" width="50px" alt="FSTatSBS" /></a>&nbsp;&nbsp;<a href="https://github.com/toverly1"><img src="https://github.com/toverly1.png" width="50px" alt="toverly1" /></a>&nbsp;&nbsp;<a href="https://github.com/ddtarazona"><img src="https://github.com/ddtarazona.png" width="50px" alt="ddtarazona" /></a>&nbsp;&nbsp;<a href="https://github.com/Nalhos"><img src="https://github.com/Nalhos.png" width="50px" alt="Nalhos" /></a>&nbsp;&nbsp;<a href="https://github.com/Kazamario"><img src="https://github.com/Kazamario.png" width="50px" alt="Kazamario" /></a>&nbsp;&nbsp;<a href="https://github.com/pingbotan"><img src="https://github.com/pingbotan.png" width="50px" alt="pingbotan" /></a>&nbsp;&nbsp;<a href="https://github.com/indoor47"><img src="https://github.com/indoor47.png" width="50px" alt="indoor47" /></a>&nbsp;&nbsp;<a href="https://github.com/AuroraHolding"><img src="https://github.com/AuroraHolding.png" width="50px" alt="AuroraHolding" /></a>&nbsp;&nbsp;<a href="https://github.com/kreativai"><img src="https://github.com/kreativai.png" width="50px" alt="kreativai" /></a>&nbsp;&nbsp;<a href="https://github.com/hunteraraujo"><img src="https://github.com/hunteraraujo.png" width="50px" alt="hunteraraujo" /></a>&nbsp;&nbsp;<a href="https://github.com/Explorergt92"><img src="https://github.com/Explorergt92.png" width="50px" alt="Explorergt92" /></a>&nbsp;&nbsp;<a href="https://github.com/judegomila"><img src="https://github.com/judegomila.png" width="50px" alt="judegomila" /></a>&nbsp;&nbsp;
51
+ <a href="https://github.com/thepok"><img src="https://github.com/thepok.png" width="50px" alt="thepok" /></a>
52
+ &nbsp;&nbsp;<a href="https://github.com/SpacingLily"><img src="https://github.com/SpacingLily.png" width="50px" alt="SpacingLily" /></a>&nbsp;&nbsp;<a href="https://github.com/merwanehamadi"><img src="https://github.com/merwanehamadi.png" width="50px" alt="merwanehamadi" /></a>&nbsp;&nbsp;<a href="https://github.com/m"><img src="https://github.com/m.png" width="50px" alt="m" /></a>&nbsp;&nbsp;<a href="https://github.com/zkonduit"><img src="https://github.com/zkonduit.png" width="50px" alt="zkonduit" /></a>&nbsp;&nbsp;<a href="https://github.com/maxxflyer"><img src="https://github.com/maxxflyer.png" width="50px" alt="maxxflyer" /></a>&nbsp;&nbsp;<a href="https://github.com/tekelsey"><img src="https://github.com/tekelsey.png" width="50px" alt="tekelsey" /></a>&nbsp;&nbsp;<a href="https://github.com/digisomni"><img src="https://github.com/digisomni.png" width="50px" alt="digisomni" /></a>&nbsp;&nbsp;<a href="https://github.com/nocodeclarity"><img src="https://github.com/nocodeclarity.png" width="50px" alt="nocodeclarity" /></a>&nbsp;&nbsp;<a href="https://github.com/tjarmain"><img src="https://github.com/tjarmain.png" width="50px" alt="tjarmain" /></a>
53
+ </p>
54
+
55
+ ## Table of Contents
56
+
57
+ - [Auto-GPT: An Autonomous GPT-4 Experiment](#auto-gpt-an-autonomous-gpt-4-experiment)
58
+ - [🔴 🔴 🔴 Urgent: USE `stable` not `master` 🔴 🔴 🔴](#----urgent-use-stable-not-master----)
59
+ - [Demo (30/03/2023):](#demo-30032023)
60
+ - [Table of Contents](#table-of-contents)
61
+ - [🚀 Features](#-features)
62
+ - [📋 Requirements](#-requirements)
63
+ - [💾 Installation](#-installation)
64
+ - [🔧 Usage](#-usage)
65
+ - [Logs](#logs)
66
+ - [Docker](#docker)
67
+ - [Command Line Arguments](#command-line-arguments)
68
+ - [🗣️ Speech Mode](#️-speech-mode)
69
+ - [🔍 Google API Keys Configuration](#-google-api-keys-configuration)
70
+ - [Setting up environment variables](#setting-up-environment-variables)
71
+ - [Memory Backend Setup](#memory-backend-setup)
72
+ - [Redis Setup](#redis-setup)
73
+ - [🌲 Pinecone API Key Setup](#-pinecone-api-key-setup)
74
+ - [Milvus Setup](#milvus-setup)
75
+ - [Setting up environment variables](#setting-up-environment-variables-1)
76
+ - [Setting Your Cache Type](#setting-your-cache-type)
77
+ - [View Memory Usage](#view-memory-usage)
78
+ - [🧠 Memory pre-seeding](#-memory-pre-seeding)
79
+ - [💀 Continuous Mode ⚠️](#-continuous-mode-️)
80
+ - [GPT3.5 ONLY Mode](#gpt35-only-mode)
81
+ - [🖼 Image Generation](#-image-generation)
82
+ - [⚠️ Limitations](#️-limitations)
83
+ - [🛡 Disclaimer](#-disclaimer)
84
+ - [🐦 Connect with Us on Twitter](#-connect-with-us-on-twitter)
85
+ - [Run tests](#run-tests)
86
+ - [Run linter](#run-linter)
87
+
88
+ ## 🚀 Features
89
+
90
+ - 🌐 Internet access for searches and information gathering
91
+ - 💾 Long-Term and Short-Term memory management
92
+ - 🧠 GPT-4 instances for text generation
93
+ - 🔗 Access to popular websites and platforms
94
+ - 🗃️ File storage and summarization with GPT-3.5
95
+
96
+ ## 📋 Requirements
97
+
98
+ - environments(just choose one)
99
+ - [vscode + devcontainer](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers): It has been configured in the .devcontainer folder and can be used directly
100
+ - [Python 3.8 or later](https://www.tutorialspoint.com/how-to-install-python-in-windows)
101
+ - [OpenAI API key](https://platform.openai.com/account/api-keys)
102
+
103
+ Optional:
104
+
105
+ - Memory backend
106
+ - [PINECONE API key](https://www.pinecone.io/) (If you want Pinecone backed memory)
107
+ - [Milvus](https://milvus.io/) (If you want Milvus as memory backend)
108
+ - ElevenLabs Key (If you want the AI to speak)
109
+
110
+ ## 💾 Installation
111
+
112
+ To install Auto-GPT, follow these steps:
113
+
114
+ 1. Make sure you have all the **requirements** listed above, if not, install/get them
115
+
116
+ _To execute the following commands, open a CMD, Bash, or Powershell window by navigating to a folder on your computer and typing `CMD` in the folder path at the top, then press enter._
117
+
118
+ 2. Clone the repository: For this step, you need Git installed. Alternatively, you can download the zip file by clicking the button at the top of this page ☝️
119
+
120
+ ```bash
121
+ git clone https://github.com/Torantulino/Auto-GPT.git
122
+ ```
123
+
124
+ 3. Navigate to the directory where the repository was downloaded
125
+
126
+ ```bash
127
+ cd Auto-GPT
128
+ ```
129
+
130
+ 4. Install the required dependencies
131
+
132
+ ```bash
133
+ pip install -r requirements.txt
134
+ ```
135
+
136
+ 5. Rename `.env.template` to `.env` and fill in your `OPENAI_API_KEY`. If you plan to use Speech Mode, fill in your `ELEVENLABS_API_KEY` as well.
137
+ - See [OpenAI API Keys Configuration](#openai-api-keys-configuration) to obtain your OpenAI API key.
138
+ - Obtain your ElevenLabs API key from: https://elevenlabs.io. You can view your xi-api-key using the "Profile" tab on the website.
139
+ - If you want to use GPT on an Azure instance, set `USE_AZURE` to `True` and then follow these steps:
140
+ - Rename `azure.yaml.template` to `azure.yaml` and provide the relevant `azure_api_base`, `azure_api_version` and all the deployment IDs for the relevant models in the `azure_model_map` section:
141
+ - `fast_llm_model_deployment_id` - your gpt-3.5-turbo or gpt-4 deployment ID
142
+ - `smart_llm_model_deployment_id` - your gpt-4 deployment ID
143
+ - `embedding_model_deployment_id` - your text-embedding-ada-002 v2 deployment ID
144
+ - Please specify all of these values as double-quoted strings
145
+ > Replace string in angled brackets (<>) to your own ID
146
+ ```yaml
147
+ azure_model_map:
148
+ fast_llm_model_deployment_id: "<my-fast-llm-deployment-id>"
149
+ ...
150
+ ```
151
+ - Details can be found here: https://pypi.org/project/openai/ in the `Microsoft Azure Endpoints` section and here: https://learn.microsoft.com/en-us/azure/cognitive-services/openai/tutorials/embeddings?tabs=command-line for the embedding model.
152
+
153
+ ## 🔧 Usage
154
+
155
+ 1. Run `autogpt` Python module in your terminal
156
+
157
+ ```
158
+ python -m autogpt
159
+ ```
160
+
161
+ 2. After each action, choose from options to authorize command(s),
162
+ exit the program, or provide feedback to the AI.
163
+ 1. Authorize a single command, enter `y`
164
+ 2. Authorize a series of _N_ continuous commands, enter `y -N`
165
+ 3. Exit the program, enter `n`
166
+
167
+
168
+ ### Logs
169
+
170
+ Activity and error logs are located in the `./output/logs`
171
+
172
+ To print out debug logs:
173
+
174
+ ```
175
+ python -m autogpt --debug
176
+ ```
177
+
178
+ ### Docker
179
+
180
+ You can also build this into a docker image and run it:
181
+
182
+ ```
183
+ docker build -t autogpt .
184
+ docker run -it --env-file=./.env -v $PWD/auto_gpt_workspace:/app/auto_gpt_workspace autogpt
185
+ ```
186
+
187
+ You can pass extra arguments, for instance, running with `--gpt3only` and `--continuous` mode:
188
+ ```
189
+ docker run -it --env-file=./.env -v $PWD/auto_gpt_workspace:/app/auto_gpt_workspace autogpt --gpt3only --continuous
190
+ ```
191
+ ### Command Line Arguments
192
+ Here are some common arguments you can use when running Auto-GPT:
193
+ > Replace anything in angled brackets (<>) to a value you want to specify
194
+ * View all available command line arguments
195
+ ```bash
196
+ python scripts/main.py --help
197
+ ```
198
+ * Run Auto-GPT with a different AI Settings file
199
+ ```bash
200
+ python scripts/main.py --ai-settings <filename>
201
+ ```
202
+ * Specify one of 3 memory backends: `local`, `redis`, `pinecone` or `no_memory`
203
+ ```bash
204
+ python scripts/main.py --use-memory <memory-backend>
205
+ ```
206
+
207
+ > **NOTE**: There are shorthands for some of these flags, for example `-m` for `--use-memory`. Use `python scripts/main.py --help` for more information
208
+
209
+ ## 🗣️ Speech Mode
210
+
211
+ Use this to use TTS _(Text-to-Speech)_ for Auto-GPT
212
+
213
+ ```bash
214
+ python -m autogpt --speak
215
+ ```
216
+
217
+ ## OpenAI API Keys Configuration
218
+
219
+ Obtain your OpenAI API key from: https://platform.openai.com/account/api-keys.
220
+
221
+ To use OpenAI API key for Auto-GPT, you NEED to have billing set up (AKA paid account).
222
+
223
+ You can set up paid account at https://platform.openai.com/account/billing/overview.
224
+
225
+ ![For OpenAI API key to work, set up paid account at OpenAI API > Billing](./docs/imgs/openai-api-key-billing-paid-account.png)
226
+
227
+
228
+ ## 🔍 Google API Keys Configuration
229
+
230
+ This section is optional, use the official google api if you are having issues with error 429 when running a google search.
231
+ To use the `google_official_search` command, you need to set up your Google API keys in your environment variables.
232
+
233
+ 1. Go to the [Google Cloud Console](https://console.cloud.google.com/).
234
+ 2. If you don't already have an account, create one and log in.
235
+ 3. Create a new project by clicking on the "Select a Project" dropdown at the top of the page and clicking "New Project". Give it a name and click "Create".
236
+ 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".
237
+ 5. Go to the [Credentials](https://console.cloud.google.com/apis/credentials) page and click "Create Credentials". Choose "API Key".
238
+ 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.
239
+ 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)
240
+ 8. Go to the [Custom Search Engine](https://cse.google.com/cse/all) page and click "Add".
241
+ 9. Set up your search engine by following the prompts. You can choose to search the entire web or specific sites.
242
+ 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.
243
+
244
+ _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._
245
+
246
+ ### Setting up environment variables
247
+
248
+ For Windows Users:
249
+
250
+ ```bash
251
+ setx GOOGLE_API_KEY "YOUR_GOOGLE_API_KEY"
252
+ setx CUSTOM_SEARCH_ENGINE_ID "YOUR_CUSTOM_SEARCH_ENGINE_ID"
253
+ ```
254
+
255
+ For macOS and Linux users:
256
+
257
+ ```bash
258
+ export GOOGLE_API_KEY="YOUR_GOOGLE_API_KEY"
259
+ export CUSTOM_SEARCH_ENGINE_ID="YOUR_CUSTOM_SEARCH_ENGINE_ID"
260
+ ```
261
+
262
+ ## Redis Setup
263
+ > _**CAUTION**_ \
264
+ 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
265
+ 1. Install docker desktop
266
+ ```bash
267
+ docker run -d --name redis-stack-server -p 6379:6379 redis/redis-stack-server:latest
268
+ ```
269
+ > See https://hub.docker.com/r/redis/redis-stack-server for setting a password and additional configuration.
270
+
271
+ 2. Set the following environment variables
272
+ > Replace **PASSWORD** in angled brackets (<>)
273
+ ```bash
274
+ MEMORY_BACKEND=redis
275
+ REDIS_HOST=localhost
276
+ REDIS_PORT=6379
277
+ REDIS_PASSWORD=<PASSWORD>
278
+ ```
279
+ You can optionally set
280
+
281
+ ```bash
282
+ WIPE_REDIS_ON_START=False
283
+ ```
284
+
285
+ To persist memory stored in Redis
286
+
287
+ You can specify the memory index for redis using the following:
288
+
289
+ ```bash
290
+ MEMORY_INDEX=<WHATEVER>
291
+ ```
292
+
293
+ ### 🌲 Pinecone API Key Setup
294
+
295
+ Pinecone enables the storage of vast amounts of vector-based memory, allowing for only relevant memories to be loaded for the agent at any given time.
296
+
297
+ 1. Go to [pinecone](https://app.pinecone.io/) and make an account if you don't already have one.
298
+ 2. Choose the `Starter` plan to avoid being charged.
299
+ 3. Find your API key and region under the default project in the left sidebar.
300
+
301
+ ### Milvus Setup
302
+
303
+ [Milvus](https://milvus.io/) is a open-source, high scalable vector database to storage huge amount of vector-based memory and provide fast relevant search.
304
+
305
+ - setup milvus database, keep your pymilvus version and milvus version same to avoid compatible issues.
306
+ - setup by open source [Install Milvus](https://milvus.io/docs/install_standalone-operator.md)
307
+ - or setup by [Zilliz Cloud](https://zilliz.com/cloud)
308
+ - set `MILVUS_ADDR` in `.env` to your milvus address `host:ip`.
309
+ - set `MEMORY_BACKEND` in `.env` to `milvus` to enable milvus as backend.
310
+ - optional
311
+ - set `MILVUS_COLLECTION` in `.env` to change milvus collection name as you want, `autogpt` is the default name.
312
+
313
+ ### Setting up environment variables
314
+
315
+ In the `.env` file set:
316
+ - `PINECONE_API_KEY`
317
+ - `PINECONE_ENV` (example: _"us-east4-gcp"_)
318
+ - `MEMORY_BACKEND=pinecone`
319
+
320
+ Alternatively, you can set them from the command line (advanced):
321
+
322
+ For Windows Users:
323
+
324
+ ```bash
325
+ setx PINECONE_API_KEY "<YOUR_PINECONE_API_KEY>"
326
+ setx PINECONE_ENV "<YOUR_PINECONE_REGION>" # e.g: "us-east4-gcp"
327
+ setx MEMORY_BACKEND "pinecone"
328
+ ```
329
+
330
+ For macOS and Linux users:
331
+
332
+ ```bash
333
+ export PINECONE_API_KEY="<YOUR_PINECONE_API_KEY>"
334
+ export PINECONE_ENV="<YOUR_PINECONE_REGION>" # e.g: "us-east4-gcp"
335
+ export MEMORY_BACKEND="pinecone"
336
+ ```
337
+
338
+ ## Setting Your Cache Type
339
+
340
+ By default, Auto-GPT is going to use LocalCache instead of redis or Pinecone.
341
+
342
+ To switch to either, change the `MEMORY_BACKEND` env variable to the value that you want:
343
+
344
+ `local` (default) uses a local JSON cache file
345
+ `pinecone` uses the Pinecone.io account you configured in your ENV settings
346
+ `redis` will use the redis cache that you configured
347
+
348
+ ## View Memory Usage
349
+
350
+ 1. View memory usage by using the `--debug` flag :)
351
+
352
+
353
+ ## 🧠 Memory pre-seeding
354
+
355
+ # python autogpt/data_ingestion.py -h
356
+ usage: data_ingestion.py [-h] (--file FILE | --dir DIR) [--init] [--overlap OVERLAP] [--max_length MAX_LENGTH]
357
+
358
+ Ingest a file or a directory with multiple files into memory. Make sure to set your .env before running this script.
359
+
360
+ options:
361
+ -h, --help show this help message and exit
362
+ --file FILE The file to ingest.
363
+ --dir DIR The directory containing the files to ingest.
364
+ --init Init the memory and wipe its content (default: False)
365
+ --overlap OVERLAP The overlap size between chunks when ingesting files (default: 200)
366
+ --max_length MAX_LENGTH The max_length of each chunk when ingesting files (default: 4000
367
+
368
+ # python autogpt/data_ingestion.py --dir seed_data --init --overlap 200 --max_length 1000
369
+ ```
370
+
371
+ This script located at autogpt/data_ingestion.py, allows you to ingest files into memory and pre-seed it before running Auto-GPT.
372
+
373
+ Memory pre-seeding is a technique that involves ingesting relevant documents or data into the AI's memory so that it can use this information to generate more informed and accurate responses.
374
+
375
+ To pre-seed the memory, the content of each document is split into chunks of a specified maximum length with a specified overlap between chunks, and then each chunk is added to the memory backend set in the .env file. When the AI is prompted to recall information, it can then access those pre-seeded memories to generate more informed and accurate responses.
376
+
377
+ This technique is particularly useful when working with large amounts of data or when there is specific information that the AI needs to be able to access quickly.
378
+ By pre-seeding the memory, the AI can retrieve and use this information more efficiently, saving time, API call and improving the accuracy of its responses.
379
+
380
+ You could for example download the documentation of an API, a GitHub repository, etc. and ingest it into memory before running Auto-GPT.
381
+
382
+ ⚠️ If you use Redis as your memory, make sure to run Auto-GPT with the `WIPE_REDIS_ON_START` set to `False` in your `.env` file.
383
+
384
+ ⚠️For other memory backend, we currently forcefully wipe the memory when starting Auto-GPT. To ingest data with those memory backend, you can call the `data_ingestion.py` script anytime during an Auto-GPT run.
385
+
386
+ Memories will be available to the AI immediately as they are ingested, even if ingested while Auto-GPT is running.
387
+
388
+ In the example above, the script initializes the memory, ingests all files within the `/seed_data` directory into memory with an overlap between chunks of 200 and a maximum length of each chunk of 4000.
389
+ Note that you can also use the `--file` argument to ingest a single file into memory and that the script will only ingest files within the `/auto_gpt_workspace` directory.
390
+
391
+ You can adjust the `max_length` and overlap parameters to fine-tune the way the docuents are presented to the AI when it "recall" that memory:
392
+
393
+ - Adjusting the overlap value allows the AI to access more contextual information from each chunk when recalling information, but will result in more chunks being created and therefore increase memory backend usage and OpenAI API requests.
394
+ - Reducing the `max_length` value will create more chunks, which can save prompt tokens by allowing for more message history in the context, but will also increase the number of chunks.
395
+ - Increasing the `max_length` value will provide the AI with more contextual information from each chunk, reducing the number of chunks created and saving on OpenAI API requests. However, this may also use more prompt tokens and decrease the overall context available to the AI.
396
+
397
+ ## 💀 Continuous Mode ⚠️
398
+
399
+ Run the AI **without** user authorization, 100% automated.
400
+ Continuous mode is NOT recommended.
401
+ It is potentially dangerous and may cause your AI to run forever or carry out actions you would not usually authorize.
402
+ Use at your own risk.
403
+
404
+ 1. Run the `autogpt` python module in your terminal:
405
+
406
+ ```bash
407
+ python -m autogpt --speak --continuous
408
+ ```
409
+
410
+ 2. To exit the program, press Ctrl + C
411
+
412
+ ## GPT3.5 ONLY Mode
413
+
414
+ If you don't have access to the GPT4 api, this mode will allow you to use Auto-GPT!
415
+
416
+ ```bash
417
+ python -m autogpt --speak --gpt3only
418
+ ```
419
+
420
+ It is recommended to use a virtual machine for tasks that require high security measures to prevent any potential harm to the main computer's system and data.
421
+
422
+ ## 🖼 Image Generation
423
+
424
+ By default, Auto-GPT uses DALL-e for image generation. To use Stable Diffusion, a [Hugging Face API Token](https://huggingface.co/settings/tokens) is required.
425
+
426
+ Once you have a token, set these variables in your `.env`:
427
+
428
+ ```bash
429
+ IMAGE_PROVIDER=sd
430
+ HUGGINGFACE_API_TOKEN="YOUR_HUGGINGFACE_API_TOKEN"
431
+ ```
432
+
433
+ ## Selenium
434
+ ```bash
435
+ sudo Xvfb :10 -ac -screen 0 1024x768x24 & DISPLAY=:10 <YOUR_CLIENT>
436
+ ```
437
+
438
+ ## ⚠️ Limitations
439
+
440
+ This experiment aims to showcase the potential of GPT-4 but comes with some limitations:
441
+
442
+ 1. Not a polished application or product, just an experiment
443
+ 2. May not perform well in complex, real-world business scenarios. In fact, if it actually does, please share your results!
444
+ 3. Quite expensive to run, so set and monitor your API key limits with OpenAI!
445
+
446
+ ## 🛡 Disclaimer
447
+
448
+ Disclaimer
449
+ This project, Auto-GPT, is an experimental application and is provided "as-is" without any warranty, express or implied. By using this software, you agree to assume all risks associated with its use, including but not limited to data loss, system failure, or any other issues that may arise.
450
+
451
+ The developers and contributors of this project do not accept any responsibility or liability for any losses, damages, or other consequences that may occur as a result of using this software. You are solely responsible for any decisions and actions taken based on the information provided by Auto-GPT.
452
+
453
+ **Please note that the use of the GPT-4 language model can be expensive due to its token usage.** By utilizing this project, you acknowledge that you are responsible for monitoring and managing your own token usage and the associated costs. It is highly recommended to check your OpenAI API usage regularly and set up any necessary limits or alerts to prevent unexpected charges.
454
+
455
+ As an autonomous experiment, Auto-GPT may generate content or take actions that are not in line with real-world business practices or legal requirements. It is your responsibility to ensure that any actions or decisions made based on the output of this software comply with all applicable laws, regulations, and ethical standards. The developers and contributors of this project shall not be held responsible for any consequences arising from the use of this software.
456
+
457
+ By using Auto-GPT, you agree to indemnify, defend, and hold harmless the developers, contributors, and any affiliated parties from and against any and all claims, damages, losses, liabilities, costs, and expenses (including reasonable attorneys' fees) arising from your use of this software or your violation of these terms.
458
+
459
+ ## 🐦 Connect with Us on Twitter
460
+
461
+ Stay up-to-date with the latest news, updates, and insights about Auto-GPT by following our Twitter accounts. Engage with the developer and the AI's own account for interesting discussions, project updates, and more.
462
+
463
+ - **Developer**: Follow [@siggravitas](https://twitter.com/siggravitas) for insights into the development process, project updates, and related topics from the creator of Entrepreneur-GPT.
464
+ - **Entrepreneur-GPT**: Join the conversation with the AI itself by following [@En_GPT](https://twitter.com/En_GPT). Share your experiences, discuss the AI's outputs, and engage with the growing community of users.
465
+
466
+ We look forward to connecting with you and hearing your thoughts, ideas, and experiences with Auto-GPT. Join us on Twitter and let's explore the future of AI together!
467
+
468
+ <p align="center">
469
+ <a href="https://star-history.com/#Torantulino/auto-gpt&Date">
470
+ <img src="https://api.star-history.com/svg?repos=Torantulino/auto-gpt&type=Date" alt="Star History Chart">
471
+ </a>
472
+ </p>
473
+
474
+ ## Run tests
475
+
476
+ To run tests, run the following command:
477
+
478
+ ```bash
479
+ python -m unittest discover tests
480
+ ```
481
+
482
+ To run tests and see coverage, run the following command:
483
+
484
+ ```bash
485
+ coverage run -m unittest discover tests
486
+ ```
487
+
488
+ ## Run linter
489
+
490
+ This project uses [flake8](https://flake8.pycqa.org/en/latest/) for linting. We currently use the following rules: `E303,W293,W291,W292,E305,E231,E302`. See the [flake8 rules](https://www.flake8rules.com/) for more information.
491
+
492
+ To run the linter, run the following command:
493
+
494
+ ```bash
495
+ flake8 autogpt/ tests/
496
+
497
+ # Or, if you want to run flake8 with the same configuration as the CI:
498
+ flake8 autogpt/ tests/ --select E303,W293,W291,W292,E305,E231,E302
499
+ ```
autogpt/agent/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from autogpt.agent.agent import Agent
2
+ from autogpt.agent.agent_manager import AgentManager
3
+
4
+ __all__ = ["Agent", "AgentManager"]
autogpt/agent/agent.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from colorama import Fore, Style
2
+ from autogpt.app import execute_command, get_command
3
+
4
+ from autogpt.chat import chat_with_ai, create_chat_message
5
+ from autogpt.config import Config
6
+ from autogpt.json_fixes.bracket_termination import (
7
+ attempt_to_fix_json_by_finding_outermost_brackets,
8
+ )
9
+ from autogpt.logs import logger, print_assistant_thoughts
10
+ from autogpt.speech import say_text
11
+ from autogpt.spinner import Spinner
12
+ from autogpt.utils import clean_input
13
+
14
+
15
+ class Agent:
16
+ """Agent class for interacting with Auto-GPT.
17
+
18
+ Attributes:
19
+ ai_name: The name of the agent.
20
+ memory: The memory object to use.
21
+ full_message_history: The full message history.
22
+ next_action_count: The number of actions to execute.
23
+ prompt: The prompt to use.
24
+ user_input: The user input.
25
+
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ ai_name,
31
+ memory,
32
+ full_message_history,
33
+ next_action_count,
34
+ prompt,
35
+ user_input,
36
+ ):
37
+ self.ai_name = ai_name
38
+ self.memory = memory
39
+ self.full_message_history = full_message_history
40
+ self.next_action_count = next_action_count
41
+ self.prompt = prompt
42
+ self.user_input = user_input
43
+
44
+ def start_interaction_loop(self):
45
+ # Interaction Loop
46
+ cfg = Config()
47
+ loop_count = 0
48
+ command_name = None
49
+ arguments = None
50
+ while True:
51
+ # Discontinue if continuous limit is reached
52
+ loop_count += 1
53
+ if (
54
+ cfg.continuous_mode
55
+ and cfg.continuous_limit > 0
56
+ and loop_count > cfg.continuous_limit
57
+ ):
58
+ logger.typewriter_log(
59
+ "Continuous Limit Reached: ", Fore.YELLOW, f"{cfg.continuous_limit}"
60
+ )
61
+ break
62
+
63
+ # Send message to AI, get response
64
+ with Spinner("Thinking... "):
65
+ assistant_reply = chat_with_ai(
66
+ self.prompt,
67
+ self.user_input,
68
+ self.full_message_history,
69
+ self.memory,
70
+ cfg.fast_token_limit,
71
+ ) # TODO: This hardcodes the model to use GPT3.5. Make this an argument
72
+
73
+ # Print Assistant thoughts
74
+ print_assistant_thoughts(self.ai_name, assistant_reply)
75
+
76
+ # Get command name and arguments
77
+ try:
78
+ command_name, arguments = get_command(
79
+ attempt_to_fix_json_by_finding_outermost_brackets(assistant_reply)
80
+ )
81
+ if cfg.speak_mode:
82
+ say_text(f"I want to execute {command_name}")
83
+ except Exception as e:
84
+ logger.error("Error: \n", str(e))
85
+
86
+ if not cfg.continuous_mode and self.next_action_count == 0:
87
+ ### GET USER AUTHORIZATION TO EXECUTE COMMAND ###
88
+ # Get key press: Prompt the user to press enter to continue or escape
89
+ # to exit
90
+ self.user_input = ""
91
+ logger.typewriter_log(
92
+ "NEXT ACTION: ",
93
+ Fore.CYAN,
94
+ f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} "
95
+ f"ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}",
96
+ )
97
+ print(
98
+ "Enter 'y' to authorise command, 'y -N' to run N continuous "
99
+ "commands, 'n' to exit program, or enter feedback for "
100
+ f"{self.ai_name}...",
101
+ flush=True,
102
+ )
103
+ while True:
104
+ console_input = clean_input(
105
+ Fore.MAGENTA + "Input:" + Style.RESET_ALL
106
+ )
107
+ if console_input.lower().rstrip() == "y":
108
+ self.user_input = "GENERATE NEXT COMMAND JSON"
109
+ break
110
+ elif console_input.lower().startswith("y -"):
111
+ try:
112
+ self.next_action_count = abs(
113
+ int(console_input.split(" ")[1])
114
+ )
115
+ self.user_input = "GENERATE NEXT COMMAND JSON"
116
+ except ValueError:
117
+ print(
118
+ "Invalid input format. Please enter 'y -n' where n is"
119
+ " the number of continuous tasks."
120
+ )
121
+ continue
122
+ break
123
+ elif console_input.lower() == "n":
124
+ self.user_input = "EXIT"
125
+ break
126
+ else:
127
+ self.user_input = console_input
128
+ command_name = "human_feedback"
129
+ break
130
+
131
+ if self.user_input == "GENERATE NEXT COMMAND JSON":
132
+ logger.typewriter_log(
133
+ "-=-=-=-=-=-=-= COMMAND AUTHORISED BY USER -=-=-=-=-=-=-=",
134
+ Fore.MAGENTA,
135
+ "",
136
+ )
137
+ elif self.user_input == "EXIT":
138
+ print("Exiting...", flush=True)
139
+ break
140
+ else:
141
+ # Print command
142
+ logger.typewriter_log(
143
+ "NEXT ACTION: ",
144
+ Fore.CYAN,
145
+ f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL}"
146
+ f" ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}",
147
+ )
148
+
149
+ # Execute command
150
+ if command_name is not None and command_name.lower().startswith("error"):
151
+ result = (
152
+ f"Command {command_name} threw the following error: {arguments}"
153
+ )
154
+ elif command_name == "human_feedback":
155
+ result = f"Human feedback: {self.user_input}"
156
+ else:
157
+ result = (
158
+ f"Command {command_name} returned: "
159
+ f"{execute_command(command_name, arguments)}"
160
+ )
161
+ if self.next_action_count > 0:
162
+ self.next_action_count -= 1
163
+
164
+ memory_to_add = (
165
+ f"Assistant Reply: {assistant_reply} "
166
+ f"\nResult: {result} "
167
+ f"\nHuman Feedback: {self.user_input} "
168
+ )
169
+
170
+ self.memory.add(memory_to_add)
171
+
172
+ # Check if there's a result from the command append it to the message
173
+ # history
174
+ if result is not None:
175
+ self.full_message_history.append(create_chat_message("system", result))
176
+ logger.typewriter_log("SYSTEM: ", Fore.YELLOW, result)
177
+ else:
178
+ self.full_message_history.append(
179
+ create_chat_message("system", "Unable to execute command")
180
+ )
181
+ logger.typewriter_log(
182
+ "SYSTEM: ", Fore.YELLOW, "Unable to execute command"
183
+ )
autogpt/agent/agent_manager.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Agent manager for managing GPT agents"""
2
+ from typing import List, Tuple, Union
3
+ from autogpt.llm_utils import create_chat_completion
4
+ from autogpt.config.config import Singleton
5
+
6
+
7
+ class AgentManager(metaclass=Singleton):
8
+ """Agent manager for managing GPT agents"""
9
+
10
+ def __init__(self):
11
+ self.next_key = 0
12
+ self.agents = {} # key, (task, full_message_history, model)
13
+
14
+ # Create new GPT agent
15
+ # TODO: Centralise use of create_chat_completion() to globally enforce token limit
16
+
17
+ def create_agent(self, task: str, prompt: str, model: str) -> Tuple[int, str]:
18
+ """Create a new agent and return its key
19
+
20
+ Args:
21
+ task: The task to perform
22
+ prompt: The prompt to use
23
+ model: The model to use
24
+
25
+ Returns:
26
+ The key of the new agent
27
+ """
28
+ messages = [
29
+ {"role": "user", "content": prompt},
30
+ ]
31
+
32
+ # Start GPT instance
33
+ agent_reply = create_chat_completion(
34
+ model=model,
35
+ messages=messages,
36
+ )
37
+
38
+ # Update full message history
39
+ messages.append({"role": "assistant", "content": agent_reply})
40
+
41
+ key = self.next_key
42
+ # This is done instead of len(agents) to make keys unique even if agents
43
+ # are deleted
44
+ self.next_key += 1
45
+
46
+ self.agents[key] = (task, messages, model)
47
+
48
+ return key, agent_reply
49
+
50
+ def message_agent(self, key: Union[str, int], message: str) -> str:
51
+ """Send a message to an agent and return its response
52
+
53
+ Args:
54
+ key: The key of the agent to message
55
+ message: The message to send to the agent
56
+
57
+ Returns:
58
+ The agent's response
59
+ """
60
+ task, messages, model = self.agents[int(key)]
61
+
62
+ # Add user message to message history before sending to agent
63
+ messages.append({"role": "user", "content": message})
64
+
65
+ # Start GPT instance
66
+ agent_reply = create_chat_completion(
67
+ model=model,
68
+ messages=messages,
69
+ )
70
+
71
+ # Update full message history
72
+ messages.append({"role": "assistant", "content": agent_reply})
73
+
74
+ return agent_reply
75
+
76
+ def list_agents(self) -> List[Tuple[Union[str, int], str]]:
77
+ """Return a list of all agents
78
+
79
+ Returns:
80
+ A list of tuples of the form (key, task)
81
+ """
82
+
83
+ # Return a list of agent keys and their tasks
84
+ return [(key, task) for key, (task, _, _) in self.agents.items()]
85
+
86
+ def delete_agent(self, key: Union[str, int]) -> bool:
87
+ """Delete an agent from the agent manager
88
+
89
+ Args:
90
+ key: The key of the agent to delete
91
+
92
+ Returns:
93
+ True if successful, False otherwise
94
+ """
95
+
96
+ try:
97
+ del self.agents[int(key)]
98
+ return True
99
+ except KeyError:
100
+ return False
autogpt/app.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Command and Control """
2
+ import json
3
+ from typing import List, NoReturn, Union
4
+ from autogpt.agent.agent_manager import AgentManager
5
+ from autogpt.commands.evaluate_code import evaluate_code
6
+ from autogpt.commands.google_search import google_official_search, google_search
7
+ from autogpt.commands.improve_code import improve_code
8
+ from autogpt.commands.write_tests import write_tests
9
+ from autogpt.config import Config
10
+ from autogpt.commands.image_gen import generate_image
11
+ from autogpt.commands.web_requests import scrape_links, scrape_text
12
+ from autogpt.commands.execute_code import execute_python_file, execute_shell
13
+ from autogpt.commands.file_operations import (
14
+ append_to_file,
15
+ delete_file,
16
+ read_file,
17
+ search_files,
18
+ write_to_file,
19
+ )
20
+ from autogpt.json_fixes.parsing import fix_and_parse_json
21
+ from autogpt.memory import get_memory
22
+ from autogpt.processing.text import summarize_text
23
+ from autogpt.speech import say_text
24
+ from autogpt.commands.web_selenium import browse_website
25
+ from autogpt.commands.git_operations import clone_repository
26
+
27
+
28
+ CFG = Config()
29
+ AGENT_MANAGER = AgentManager()
30
+
31
+
32
+ def is_valid_int(value: str) -> bool:
33
+ """Check if the value is a valid integer
34
+
35
+ Args:
36
+ value (str): The value to check
37
+
38
+ Returns:
39
+ bool: True if the value is a valid integer, False otherwise
40
+ """
41
+ try:
42
+ int(value)
43
+ return True
44
+ except ValueError:
45
+ return False
46
+
47
+
48
+ def get_command(response: str):
49
+ """Parse the response and return the command name and arguments
50
+
51
+ Args:
52
+ response (str): The response from the user
53
+
54
+ Returns:
55
+ tuple: The command name and arguments
56
+
57
+ Raises:
58
+ json.decoder.JSONDecodeError: If the response is not valid JSON
59
+
60
+ Exception: If any other error occurs
61
+ """
62
+ try:
63
+ response_json = fix_and_parse_json(response)
64
+
65
+ if "command" not in response_json:
66
+ return "Error:", "Missing 'command' object in JSON"
67
+
68
+ if not isinstance(response_json, dict):
69
+ return "Error:", f"'response_json' object is not dictionary {response_json}"
70
+
71
+ command = response_json["command"]
72
+ if not isinstance(command, dict):
73
+ return "Error:", "'command' object is not a dictionary"
74
+
75
+ if "name" not in command:
76
+ return "Error:", "Missing 'name' field in 'command' object"
77
+
78
+ command_name = command["name"]
79
+
80
+ # Use an empty dictionary if 'args' field is not present in 'command' object
81
+ arguments = command.get("args", {})
82
+
83
+ return command_name, arguments
84
+ except json.decoder.JSONDecodeError:
85
+ return "Error:", "Invalid JSON"
86
+ # All other errors, return "Error: + error message"
87
+ except Exception as e:
88
+ return "Error:", str(e)
89
+
90
+
91
+ def map_command_synonyms(command_name: str):
92
+ """Takes the original command name given by the AI, and checks if the
93
+ string matches a list of common/known hallucinations
94
+ """
95
+ synonyms = [
96
+ ("write_file", "write_to_file"),
97
+ ("create_file", "write_to_file"),
98
+ ("search", "google"),
99
+ ]
100
+ for seen_command, actual_command_name in synonyms:
101
+ if command_name == seen_command:
102
+ return actual_command_name
103
+ return command_name
104
+
105
+
106
+ def execute_command(command_name: str, arguments):
107
+ """Execute the command and return the result
108
+
109
+ Args:
110
+ command_name (str): The name of the command to execute
111
+ arguments (dict): The arguments for the command
112
+
113
+ Returns:
114
+ str: The result of the command"""
115
+ memory = get_memory(CFG)
116
+
117
+ try:
118
+ command_name = map_command_synonyms(command_name)
119
+ if command_name == "google":
120
+ # Check if the Google API key is set and use the official search method
121
+ # If the API key is not set or has only whitespaces, use the unofficial
122
+ # search method
123
+ key = CFG.google_api_key
124
+ if key and key.strip() and key != "your-google-api-key":
125
+ google_result = google_official_search(arguments["input"])
126
+ else:
127
+ google_result = google_search(arguments["input"])
128
+ safe_message = google_result.encode("utf-8", "ignore")
129
+ return str(safe_message)
130
+ elif command_name == "memory_add":
131
+ return memory.add(arguments["string"])
132
+ elif command_name == "start_agent":
133
+ return start_agent(
134
+ arguments["name"], arguments["task"], arguments["prompt"]
135
+ )
136
+ elif command_name == "message_agent":
137
+ return message_agent(arguments["key"], arguments["message"])
138
+ elif command_name == "list_agents":
139
+ return list_agents()
140
+ elif command_name == "delete_agent":
141
+ return delete_agent(arguments["key"])
142
+ elif command_name == "get_text_summary":
143
+ return get_text_summary(arguments["url"], arguments["question"])
144
+ elif command_name == "get_hyperlinks":
145
+ return get_hyperlinks(arguments["url"])
146
+ elif command_name == "clone_repository":
147
+ return clone_repository(
148
+ arguments["repository_url"], arguments["clone_path"]
149
+ )
150
+ elif command_name == "read_file":
151
+ return read_file(arguments["file"])
152
+ elif command_name == "write_to_file":
153
+ return write_to_file(arguments["file"], arguments["text"])
154
+ elif command_name == "append_to_file":
155
+ return append_to_file(arguments["file"], arguments["text"])
156
+ elif command_name == "delete_file":
157
+ return delete_file(arguments["file"])
158
+ elif command_name == "search_files":
159
+ return search_files(arguments["directory"])
160
+ elif command_name == "browse_website":
161
+ return browse_website(arguments["url"], arguments["question"])
162
+ # TODO: Change these to take in a file rather than pasted code, if
163
+ # non-file is given, return instructions "Input should be a python
164
+ # filepath, write your code to file and try again"
165
+ elif command_name == "evaluate_code":
166
+ return evaluate_code(arguments["code"])
167
+ elif command_name == "improve_code":
168
+ return improve_code(arguments["suggestions"], arguments["code"])
169
+ elif command_name == "write_tests":
170
+ return write_tests(arguments["code"], arguments.get("focus"))
171
+ elif command_name == "execute_python_file": # Add this command
172
+ return execute_python_file(arguments["file"])
173
+ elif command_name == "execute_shell":
174
+ if CFG.execute_local_commands:
175
+ return execute_shell(arguments["command_line"])
176
+ else:
177
+ return (
178
+ "You are not allowed to run local shell commands. To execute"
179
+ " shell commands, EXECUTE_LOCAL_COMMANDS must be set to 'True' "
180
+ "in your config. Do not attempt to bypass the restriction."
181
+ )
182
+ elif command_name == "generate_image":
183
+ return generate_image(arguments["prompt"])
184
+ elif command_name == "do_nothing":
185
+ return "No action performed."
186
+ elif command_name == "task_complete":
187
+ shutdown()
188
+ else:
189
+ return (
190
+ f"Unknown command '{command_name}'. Please refer to the 'COMMANDS'"
191
+ " list for available commands and only respond in the specified JSON"
192
+ " format."
193
+ )
194
+ except Exception as e:
195
+ return f"Error: {str(e)}"
196
+
197
+
198
+ def get_text_summary(url: str, question: str) -> str:
199
+ """Return the results of a google search
200
+
201
+ Args:
202
+ url (str): The url to scrape
203
+ question (str): The question to summarize the text for
204
+
205
+ Returns:
206
+ str: The summary of the text
207
+ """
208
+ text = scrape_text(url)
209
+ summary = summarize_text(url, text, question)
210
+ return f""" "Result" : {summary}"""
211
+
212
+
213
+ def get_hyperlinks(url: str) -> Union[str, List[str]]:
214
+ """Return the results of a google search
215
+
216
+ Args:
217
+ url (str): The url to scrape
218
+
219
+ Returns:
220
+ str or list: The hyperlinks on the page
221
+ """
222
+ return scrape_links(url)
223
+
224
+
225
+ def shutdown() -> NoReturn:
226
+ """Shut down the program"""
227
+ print("Shutting down...")
228
+ quit()
229
+
230
+
231
+ def start_agent(name: str, task: str, prompt: str, model=CFG.fast_llm_model) -> str:
232
+ """Start an agent with a given name, task, and prompt
233
+
234
+ Args:
235
+ name (str): The name of the agent
236
+ task (str): The task of the agent
237
+ prompt (str): The prompt for the agent
238
+ model (str): The model to use for the agent
239
+
240
+ Returns:
241
+ str: The response of the agent
242
+ """
243
+ # Remove underscores from name
244
+ voice_name = name.replace("_", " ")
245
+
246
+ first_message = f"""You are {name}. Respond with: "Acknowledged"."""
247
+ agent_intro = f"{voice_name} here, Reporting for duty!"
248
+
249
+ # Create agent
250
+ if CFG.speak_mode:
251
+ say_text(agent_intro, 1)
252
+ key, ack = AGENT_MANAGER.create_agent(task, first_message, model)
253
+
254
+ if CFG.speak_mode:
255
+ say_text(f"Hello {voice_name}. Your task is as follows. {task}.")
256
+
257
+ # Assign task (prompt), get response
258
+ agent_response = AGENT_MANAGER.message_agent(key, prompt)
259
+
260
+ return f"Agent {name} created with key {key}. First response: {agent_response}"
261
+
262
+
263
+ def message_agent(key: str, message: str) -> str:
264
+ """Message an agent with a given key and message"""
265
+ # Check if the key is a valid integer
266
+ if is_valid_int(key):
267
+ agent_response = AGENT_MANAGER.message_agent(int(key), message)
268
+ else:
269
+ return "Invalid key, must be an integer."
270
+
271
+ # Speak response
272
+ if CFG.speak_mode:
273
+ say_text(agent_response, 1)
274
+ return agent_response
275
+
276
+
277
+ def list_agents():
278
+ """List all agents
279
+
280
+ Returns:
281
+ str: A list of all agents
282
+ """
283
+ return "List of agents:\n" + "\n".join(
284
+ [str(x[0]) + ": " + x[1] for x in AGENT_MANAGER.list_agents()]
285
+ )
286
+
287
+
288
+ def delete_agent(key: str) -> str:
289
+ """Delete an agent with a given key
290
+
291
+ Args:
292
+ key (str): The key of the agent to delete
293
+
294
+ Returns:
295
+ str: A message indicating whether the agent was deleted or not
296
+ """
297
+ result = AGENT_MANAGER.delete_agent(key)
298
+ return f"Agent {key} deleted." if result else f"Agent {key} does not exist."
autogpt/args.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """This module contains the argument parsing logic for the script."""
2
+ import argparse
3
+
4
+ from colorama import Fore
5
+ from autogpt import utils
6
+ from autogpt.config import Config
7
+ from autogpt.logs import logger
8
+ from autogpt.memory import get_supported_memory_backends
9
+
10
+ CFG = Config()
11
+
12
+
13
+ def parse_arguments() -> None:
14
+ """Parses the arguments passed to the script
15
+
16
+ Returns:
17
+ None
18
+ """
19
+ CFG.set_debug_mode(False)
20
+ CFG.set_continuous_mode(False)
21
+ CFG.set_speak_mode(False)
22
+
23
+ parser = argparse.ArgumentParser(description="Process arguments.")
24
+ parser.add_argument(
25
+ "--continuous", "-c", action="store_true", help="Enable Continuous Mode"
26
+ )
27
+ parser.add_argument(
28
+ "--continuous-limit",
29
+ "-l",
30
+ type=int,
31
+ dest="continuous_limit",
32
+ help="Defines the number of times to run in continuous mode",
33
+ )
34
+ parser.add_argument("--speak", action="store_true", help="Enable Speak Mode")
35
+ parser.add_argument("--debug", action="store_true", help="Enable Debug Mode")
36
+ parser.add_argument(
37
+ "--gpt3only", action="store_true", help="Enable GPT3.5 Only Mode"
38
+ )
39
+ parser.add_argument("--gpt4only", action="store_true", help="Enable GPT4 Only Mode")
40
+ parser.add_argument(
41
+ "--use-memory",
42
+ "-m",
43
+ dest="memory_type",
44
+ help="Defines which Memory backend to use",
45
+ )
46
+ parser.add_argument(
47
+ "--skip-reprompt",
48
+ "-y",
49
+ dest="skip_reprompt",
50
+ action="store_true",
51
+ help="Skips the re-prompting messages at the beginning of the script",
52
+ )
53
+ parser.add_argument(
54
+ "--use-browser",
55
+ "-b",
56
+ dest="browser_name",
57
+ help="Specifies which web-browser to use when using selenium to scrape the web.",
58
+ )
59
+ parser.add_argument(
60
+ "--ai-settings",
61
+ "-C",
62
+ dest="ai_settings_file",
63
+ help="Specifies which ai_settings.yaml file to use, will also automatically"
64
+ " skip the re-prompt.",
65
+ )
66
+ args = parser.parse_args()
67
+
68
+ if args.debug:
69
+ logger.typewriter_log("Debug Mode: ", Fore.GREEN, "ENABLED")
70
+ CFG.set_debug_mode(True)
71
+
72
+ if args.continuous:
73
+ logger.typewriter_log("Continuous Mode: ", Fore.RED, "ENABLED")
74
+ logger.typewriter_log(
75
+ "WARNING: ",
76
+ Fore.RED,
77
+ "Continuous mode is not recommended. It is potentially dangerous and may"
78
+ " cause your AI to run forever or carry out actions you would not usually"
79
+ " authorise. Use at your own risk.",
80
+ )
81
+ CFG.set_continuous_mode(True)
82
+
83
+ if args.continuous_limit:
84
+ logger.typewriter_log(
85
+ "Continuous Limit: ", Fore.GREEN, f"{args.continuous_limit}"
86
+ )
87
+ CFG.set_continuous_limit(args.continuous_limit)
88
+
89
+ # Check if continuous limit is used without continuous mode
90
+ if args.continuous_limit and not args.continuous:
91
+ parser.error("--continuous-limit can only be used with --continuous")
92
+
93
+ if args.speak:
94
+ logger.typewriter_log("Speak Mode: ", Fore.GREEN, "ENABLED")
95
+ CFG.set_speak_mode(True)
96
+
97
+ if args.gpt3only:
98
+ logger.typewriter_log("GPT3.5 Only Mode: ", Fore.GREEN, "ENABLED")
99
+ CFG.set_smart_llm_model(CFG.fast_llm_model)
100
+
101
+ if args.gpt4only:
102
+ logger.typewriter_log("GPT4 Only Mode: ", Fore.GREEN, "ENABLED")
103
+ CFG.set_fast_llm_model(CFG.smart_llm_model)
104
+
105
+ if args.memory_type:
106
+ supported_memory = get_supported_memory_backends()
107
+ chosen = args.memory_type
108
+ if chosen not in supported_memory:
109
+ logger.typewriter_log(
110
+ "ONLY THE FOLLOWING MEMORY BACKENDS ARE SUPPORTED: ",
111
+ Fore.RED,
112
+ f"{supported_memory}",
113
+ )
114
+ logger.typewriter_log("Defaulting to: ", Fore.YELLOW, CFG.memory_backend)
115
+ else:
116
+ CFG.memory_backend = chosen
117
+
118
+ if args.skip_reprompt:
119
+ logger.typewriter_log("Skip Re-prompt: ", Fore.GREEN, "ENABLED")
120
+ CFG.skip_reprompt = True
121
+
122
+ if args.ai_settings_file:
123
+ file = args.ai_settings_file
124
+
125
+ # Validate file
126
+ (validated, message) = utils.validate_yaml_file(file)
127
+ if not validated:
128
+ logger.typewriter_log("FAILED FILE VALIDATION", Fore.RED, message)
129
+ logger.double_check()
130
+ exit(1)
131
+
132
+ logger.typewriter_log("Using AI Settings File:", Fore.GREEN, file)
133
+ CFG.ai_settings_file = file
134
+ CFG.skip_reprompt = True
135
+
136
+ if args.browser_name:
137
+ CFG.selenium_web_browser = args.browser_name
autogpt/commands/__init__.py ADDED
File without changes
autogpt/commands/evaluate_code.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Code evaluation module."""
2
+ from typing import List
3
+
4
+ from autogpt.llm_utils import call_ai_function
5
+
6
+
7
+ def evaluate_code(code: str) -> List[str]:
8
+ """
9
+ A function that takes in a string and returns a response from create chat
10
+ completion api call.
11
+
12
+ Parameters:
13
+ code (str): Code to be evaluated.
14
+ Returns:
15
+ A result string from create chat completion. A list of suggestions to
16
+ improve the code.
17
+ """
18
+
19
+ function_string = "def analyze_code(code: str) -> List[str]:"
20
+ args = [code]
21
+ description_string = (
22
+ "Analyzes the given code and returns a list of suggestions" " for improvements."
23
+ )
24
+
25
+ return call_ai_function(function_string, args, description_string)
autogpt/commands/execute_code.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Execute code in a Docker container"""
2
+ import os
3
+ from pathlib import Path
4
+ import subprocess
5
+
6
+ import docker
7
+ from docker.errors import ImageNotFound
8
+
9
+ WORKING_DIRECTORY = Path(__file__).parent.parent / "auto_gpt_workspace"
10
+
11
+
12
+ def execute_python_file(file: str):
13
+ """Execute a Python file in a Docker container and return the output
14
+
15
+ Args:
16
+ file (str): The name of the file to execute
17
+
18
+ Returns:
19
+ str: The output of the file
20
+ """
21
+
22
+ print(f"Executing file '{file}' in workspace '{WORKING_DIRECTORY}'")
23
+
24
+ if not file.endswith(".py"):
25
+ return "Error: Invalid file type. Only .py files are allowed."
26
+
27
+ file_path = os.path.join(WORKING_DIRECTORY, file)
28
+
29
+ if not os.path.isfile(file_path):
30
+ return f"Error: File '{file}' does not exist."
31
+
32
+ if we_are_running_in_a_docker_container():
33
+ result = subprocess.run(
34
+ f"python {file_path}", capture_output=True, encoding="utf8", shell=True
35
+ )
36
+ if result.returncode == 0:
37
+ return result.stdout
38
+ else:
39
+ return f"Error: {result.stderr}"
40
+
41
+ try:
42
+ client = docker.from_env()
43
+
44
+ image_name = "python:3.10"
45
+ try:
46
+ client.images.get(image_name)
47
+ print(f"Image '{image_name}' found locally")
48
+ except ImageNotFound:
49
+ print(f"Image '{image_name}' not found locally, pulling from Docker Hub")
50
+ # Use the low-level API to stream the pull response
51
+ low_level_client = docker.APIClient()
52
+ for line in low_level_client.pull(image_name, stream=True, decode=True):
53
+ # Print the status and progress, if available
54
+ status = line.get("status")
55
+ progress = line.get("progress")
56
+ if status and progress:
57
+ print(f"{status}: {progress}")
58
+ elif status:
59
+ print(status)
60
+
61
+ # You can replace 'python:3.8' with the desired Python image/version
62
+ # You can find available Python images on Docker Hub:
63
+ # https://hub.docker.com/_/python
64
+ container = client.containers.run(
65
+ image_name,
66
+ f"python {file}",
67
+ volumes={
68
+ os.path.abspath(WORKING_DIRECTORY): {
69
+ "bind": "/workspace",
70
+ "mode": "ro",
71
+ }
72
+ },
73
+ working_dir="/workspace",
74
+ stderr=True,
75
+ stdout=True,
76
+ detach=True,
77
+ )
78
+
79
+ container.wait()
80
+ logs = container.logs().decode("utf-8")
81
+ container.remove()
82
+
83
+ # print(f"Execution complete. Output: {output}")
84
+ # print(f"Logs: {logs}")
85
+
86
+ return logs
87
+
88
+ except Exception as e:
89
+ return f"Error: {str(e)}"
90
+
91
+
92
+ def execute_shell(command_line: str) -> str:
93
+ """Execute a shell command and return the output
94
+
95
+ Args:
96
+ command_line (str): The command line to execute
97
+
98
+ Returns:
99
+ str: The output of the command
100
+ """
101
+ current_dir = os.getcwd()
102
+ # Change dir into workspace if necessary
103
+ if str(WORKING_DIRECTORY) not in current_dir:
104
+ work_dir = os.path.join(os.getcwd(), WORKING_DIRECTORY)
105
+ os.chdir(work_dir)
106
+
107
+ print(f"Executing command '{command_line}' in working directory '{os.getcwd()}'")
108
+
109
+ result = subprocess.run(command_line, capture_output=True, shell=True)
110
+ output = f"STDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}"
111
+
112
+ # Change back to whatever the prior working dir was
113
+
114
+ os.chdir(current_dir)
115
+
116
+ return output
117
+
118
+
119
+ def we_are_running_in_a_docker_container() -> bool:
120
+ """Check if we are running in a Docker container
121
+
122
+ Returns:
123
+ bool: True if we are running in a Docker container, False otherwise
124
+ """
125
+ return os.path.exists("/.dockerenv")
autogpt/commands/file_operations.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """File operations for AutoGPT"""
2
+ import os
3
+ import os.path
4
+ from pathlib import Path
5
+ from typing import Generator, List
6
+
7
+ # Set a dedicated folder for file I/O
8
+ WORKING_DIRECTORY = Path(__file__).parent.parent / "auto_gpt_workspace"
9
+
10
+ # Create the directory if it doesn't exist
11
+ if not os.path.exists(WORKING_DIRECTORY):
12
+ os.makedirs(WORKING_DIRECTORY)
13
+
14
+ WORKING_DIRECTORY = str(WORKING_DIRECTORY)
15
+
16
+
17
+ def safe_join(base: str, *paths) -> str:
18
+ """Join one or more path components intelligently.
19
+
20
+ Args:
21
+ base (str): The base path
22
+ *paths (str): The paths to join to the base path
23
+
24
+ Returns:
25
+ str: The joined path
26
+ """
27
+ new_path = os.path.join(base, *paths)
28
+ norm_new_path = os.path.normpath(new_path)
29
+
30
+ if os.path.commonprefix([base, norm_new_path]) != base:
31
+ raise ValueError("Attempted to access outside of working directory.")
32
+
33
+ return norm_new_path
34
+
35
+
36
+ def split_file(
37
+ content: str, max_length: int = 4000, overlap: int = 0
38
+ ) -> Generator[str, None, None]:
39
+ """
40
+ Split text into chunks of a specified maximum length with a specified overlap
41
+ between chunks.
42
+
43
+ :param content: The input text to be split into chunks
44
+ :param max_length: The maximum length of each chunk,
45
+ default is 4000 (about 1k token)
46
+ :param overlap: The number of overlapping characters between chunks,
47
+ default is no overlap
48
+ :return: A generator yielding chunks of text
49
+ """
50
+ start = 0
51
+ content_length = len(content)
52
+
53
+ while start < content_length:
54
+ end = start + max_length
55
+ if end + overlap < content_length:
56
+ chunk = content[start : end + overlap]
57
+ else:
58
+ chunk = content[start:content_length]
59
+ yield chunk
60
+ start += max_length - overlap
61
+
62
+
63
+ def read_file(filename: str) -> str:
64
+ """Read a file and return the contents
65
+
66
+ Args:
67
+ filename (str): The name of the file to read
68
+
69
+ Returns:
70
+ str: The contents of the file
71
+ """
72
+ try:
73
+ filepath = safe_join(WORKING_DIRECTORY, filename)
74
+ with open(filepath, "r", encoding="utf-8") as f:
75
+ content = f.read()
76
+ return content
77
+ except Exception as e:
78
+ return f"Error: {str(e)}"
79
+
80
+
81
+ def ingest_file(
82
+ filename: str, memory, max_length: int = 4000, overlap: int = 200
83
+ ) -> None:
84
+ """
85
+ Ingest a file by reading its content, splitting it into chunks with a specified
86
+ maximum length and overlap, and adding the chunks to the memory storage.
87
+
88
+ :param filename: The name of the file to ingest
89
+ :param memory: An object with an add() method to store the chunks in memory
90
+ :param max_length: The maximum length of each chunk, default is 4000
91
+ :param overlap: The number of overlapping characters between chunks, default is 200
92
+ """
93
+ try:
94
+ print(f"Working with file {filename}")
95
+ content = read_file(filename)
96
+ content_length = len(content)
97
+ print(f"File length: {content_length} characters")
98
+
99
+ chunks = list(split_file(content, max_length=max_length, overlap=overlap))
100
+
101
+ num_chunks = len(chunks)
102
+ for i, chunk in enumerate(chunks):
103
+ print(f"Ingesting chunk {i + 1} / {num_chunks} into memory")
104
+ memory_to_add = (
105
+ f"Filename: {filename}\n" f"Content part#{i + 1}/{num_chunks}: {chunk}"
106
+ )
107
+
108
+ memory.add(memory_to_add)
109
+
110
+ print(f"Done ingesting {num_chunks} chunks from {filename}.")
111
+ except Exception as e:
112
+ print(f"Error while ingesting file '{filename}': {str(e)}")
113
+
114
+
115
+ def write_to_file(filename: str, text: str) -> str:
116
+ """Write text to a file
117
+
118
+ Args:
119
+ filename (str): The name of the file to write to
120
+ text (str): The text to write to the file
121
+
122
+ Returns:
123
+ str: A message indicating success or failure
124
+ """
125
+ try:
126
+ filepath = safe_join(WORKING_DIRECTORY, filename)
127
+ directory = os.path.dirname(filepath)
128
+ if not os.path.exists(directory):
129
+ os.makedirs(directory)
130
+ with open(filepath, "w", encoding="utf-8") as f:
131
+ f.write(text)
132
+ return "File written to successfully."
133
+ except Exception as e:
134
+ return f"Error: {str(e)}"
135
+
136
+
137
+ def append_to_file(filename: str, text: str) -> str:
138
+ """Append text to a file
139
+
140
+ Args:
141
+ filename (str): The name of the file to append to
142
+ text (str): The text to append to the file
143
+
144
+ Returns:
145
+ str: A message indicating success or failure
146
+ """
147
+ try:
148
+ filepath = safe_join(WORKING_DIRECTORY, filename)
149
+ with open(filepath, "a") as f:
150
+ f.write(text)
151
+ return "Text appended successfully."
152
+ except Exception as e:
153
+ return f"Error: {str(e)}"
154
+
155
+
156
+ def delete_file(filename: str) -> str:
157
+ """Delete a file
158
+
159
+ Args:
160
+ filename (str): The name of the file to delete
161
+
162
+ Returns:
163
+ str: A message indicating success or failure
164
+ """
165
+ try:
166
+ filepath = safe_join(WORKING_DIRECTORY, filename)
167
+ os.remove(filepath)
168
+ return "File deleted successfully."
169
+ except Exception as e:
170
+ return f"Error: {str(e)}"
171
+
172
+
173
+ def search_files(directory: str) -> List[str]:
174
+ """Search for files in a directory
175
+
176
+ Args:
177
+ directory (str): The directory to search in
178
+
179
+ Returns:
180
+ List[str]: A list of files found in the directory
181
+ """
182
+ found_files = []
183
+
184
+ if directory in {"", "/"}:
185
+ search_directory = WORKING_DIRECTORY
186
+ else:
187
+ search_directory = safe_join(WORKING_DIRECTORY, directory)
188
+
189
+ for root, _, files in os.walk(search_directory):
190
+ for file in files:
191
+ if file.startswith("."):
192
+ continue
193
+ relative_path = os.path.relpath(os.path.join(root, file), WORKING_DIRECTORY)
194
+ found_files.append(relative_path)
195
+
196
+ return found_files
autogpt/commands/git_operations.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Git operations for autogpt"""
2
+ import git
3
+ from autogpt.config import Config
4
+
5
+ CFG = Config()
6
+
7
+
8
+ def clone_repository(repo_url: str, clone_path: str) -> str:
9
+ """Clone a github repository locally
10
+
11
+ Args:
12
+ repo_url (str): The URL of the repository to clone
13
+ clone_path (str): The path to clone the repository to
14
+
15
+ Returns:
16
+ str: The result of the clone operation"""
17
+ split_url = repo_url.split("//")
18
+ auth_repo_url = f"//{CFG.github_username}:{CFG.github_api_key}@".join(split_url)
19
+ git.Repo.clone_from(auth_repo_url, clone_path)
20
+ return f"""Cloned {repo_url} to {clone_path}"""
autogpt/commands/google_search.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Google search command for Autogpt."""
2
+ import json
3
+ from typing import List, Union
4
+
5
+ from duckduckgo_search import ddg
6
+
7
+ from autogpt.config import Config
8
+
9
+ CFG = Config()
10
+
11
+
12
+ def google_search(query: str, num_results: int = 8) -> str:
13
+ """Return the results of a google search
14
+
15
+ Args:
16
+ query (str): The search query.
17
+ num_results (int): The number of results to return.
18
+
19
+ Returns:
20
+ str: The results of the search.
21
+ """
22
+ search_results = []
23
+ if not query:
24
+ return json.dumps(search_results)
25
+
26
+ results = ddg(query, max_results=num_results)
27
+ if not results:
28
+ return json.dumps(search_results)
29
+
30
+ for j in results:
31
+ search_results.append(j)
32
+
33
+ return json.dumps(search_results, ensure_ascii=False, indent=4)
34
+
35
+
36
+ def google_official_search(query: str, num_results: int = 8) -> Union[str, List[str]]:
37
+ """Return the results of a google search using the official Google API
38
+
39
+ Args:
40
+ query (str): The search query.
41
+ num_results (int): The number of results to return.
42
+
43
+ Returns:
44
+ str: The results of the search.
45
+ """
46
+
47
+ from googleapiclient.discovery import build
48
+ from googleapiclient.errors import HttpError
49
+
50
+ try:
51
+ # Get the Google API key and Custom Search Engine ID from the config file
52
+ api_key = CFG.google_api_key
53
+ custom_search_engine_id = CFG.custom_search_engine_id
54
+
55
+ # Initialize the Custom Search API service
56
+ service = build("customsearch", "v1", developerKey=api_key)
57
+
58
+ # Send the search query and retrieve the results
59
+ result = (
60
+ service.cse()
61
+ .list(q=query, cx=custom_search_engine_id, num=num_results)
62
+ .execute()
63
+ )
64
+
65
+ # Extract the search result items from the response
66
+ search_results = result.get("items", [])
67
+
68
+ # Create a list of only the URLs from the search results
69
+ search_results_links = [item["link"] for item in search_results]
70
+
71
+ except HttpError as e:
72
+ # Handle errors in the API call
73
+ error_details = json.loads(e.content.decode())
74
+
75
+ # Check if the error is related to an invalid or missing API key
76
+ if error_details.get("error", {}).get(
77
+ "code"
78
+ ) == 403 and "invalid API key" in error_details.get("error", {}).get(
79
+ "message", ""
80
+ ):
81
+ return "Error: The provided Google API key is invalid or missing."
82
+ else:
83
+ return f"Error: {e}"
84
+
85
+ # Return the list of search result URLs
86
+ return search_results_links
autogpt/commands/image_gen.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Image Generation Module for AutoGPT."""
2
+ import io
3
+ import os.path
4
+ import uuid
5
+ from base64 import b64decode
6
+
7
+ import openai
8
+ import requests
9
+ from PIL import Image
10
+ from pathlib import Path
11
+ from autogpt.config import Config
12
+
13
+ CFG = Config()
14
+
15
+ WORKING_DIRECTORY = Path(__file__).parent.parent / "auto_gpt_workspace"
16
+
17
+
18
+ def generate_image(prompt: str) -> str:
19
+ """Generate an image from a prompt.
20
+
21
+ Args:
22
+ prompt (str): The prompt to use
23
+
24
+ Returns:
25
+ str: The filename of the image
26
+ """
27
+ filename = f"{str(uuid.uuid4())}.jpg"
28
+
29
+ # DALL-E
30
+ if CFG.image_provider == "dalle":
31
+ return generate_image_with_dalle(prompt, filename)
32
+ elif CFG.image_provider == "sd":
33
+ return generate_image_with_hf(prompt, filename)
34
+ else:
35
+ return "No Image Provider Set"
36
+
37
+
38
+ def generate_image_with_hf(prompt: str, filename: str) -> str:
39
+ """Generate an image with HuggingFace's API.
40
+
41
+ Args:
42
+ prompt (str): The prompt to use
43
+ filename (str): The filename to save the image to
44
+
45
+ Returns:
46
+ str: The filename of the image
47
+ """
48
+ API_URL = (
49
+ "https://api-inference.huggingface.co/models/CompVis/stable-diffusion-v1-4"
50
+ )
51
+ if CFG.huggingface_api_token is None:
52
+ raise ValueError(
53
+ "You need to set your Hugging Face API token in the config file."
54
+ )
55
+ headers = {"Authorization": f"Bearer {CFG.huggingface_api_token}"}
56
+
57
+ response = requests.post(
58
+ API_URL,
59
+ headers=headers,
60
+ json={
61
+ "inputs": prompt,
62
+ },
63
+ )
64
+
65
+ image = Image.open(io.BytesIO(response.content))
66
+ print(f"Image Generated for prompt:{prompt}")
67
+
68
+ image.save(os.path.join(WORKING_DIRECTORY, filename))
69
+
70
+ return f"Saved to disk:{filename}"
71
+
72
+
73
+ def generate_image_with_dalle(prompt: str, filename: str) -> str:
74
+ """Generate an image with DALL-E.
75
+
76
+ Args:
77
+ prompt (str): The prompt to use
78
+ filename (str): The filename to save the image to
79
+
80
+ Returns:
81
+ str: The filename of the image
82
+ """
83
+ openai.api_key = CFG.openai_api_key
84
+
85
+ response = openai.Image.create(
86
+ prompt=prompt,
87
+ n=1,
88
+ size="256x256",
89
+ response_format="b64_json",
90
+ )
91
+
92
+ print(f"Image Generated for prompt:{prompt}")
93
+
94
+ image_data = b64decode(response["data"][0]["b64_json"])
95
+
96
+ with open(f"{WORKING_DIRECTORY}/{filename}", mode="wb") as png:
97
+ png.write(image_data)
98
+
99
+ return f"Saved to disk:{filename}"
autogpt/commands/improve_code.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from typing import List
3
+
4
+ from autogpt.llm_utils import call_ai_function
5
+
6
+
7
+ def improve_code(suggestions: List[str], code: str) -> str:
8
+ """
9
+ A function that takes in code and suggestions and returns a response from create
10
+ chat completion api call.
11
+
12
+ Parameters:
13
+ suggestions (List): A list of suggestions around what needs to be improved.
14
+ code (str): Code to be improved.
15
+ Returns:
16
+ A result string from create chat completion. Improved code in response.
17
+ """
18
+
19
+ function_string = (
20
+ "def generate_improved_code(suggestions: List[str], code: str) -> str:"
21
+ )
22
+ args = [json.dumps(suggestions), code]
23
+ description_string = (
24
+ "Improves the provided code based on the suggestions"
25
+ " provided, making no other changes."
26
+ )
27
+
28
+ return call_ai_function(function_string, args, description_string)
autogpt/commands/times.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+
3
+
4
+ def get_datetime() -> str:
5
+ """Return the current date and time
6
+
7
+ Returns:
8
+ str: The current date and time
9
+ """
10
+ return "Current date and time: " + datetime.now().strftime("%Y-%m-%d %H:%M:%S")
autogpt/commands/web_playwright.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Web scraping commands using Playwright"""
2
+ try:
3
+ from playwright.sync_api import sync_playwright
4
+ except ImportError:
5
+ print(
6
+ "Playwright not installed. Please install it with 'pip install playwright' to use."
7
+ )
8
+ from bs4 import BeautifulSoup
9
+ from autogpt.processing.html import extract_hyperlinks, format_hyperlinks
10
+ from typing import List, Union
11
+
12
+
13
+ def scrape_text(url: str) -> str:
14
+ """Scrape text from a webpage
15
+
16
+ Args:
17
+ url (str): The URL to scrape text from
18
+
19
+ Returns:
20
+ str: The scraped text
21
+ """
22
+ with sync_playwright() as p:
23
+ browser = p.chromium.launch()
24
+ page = browser.new_page()
25
+
26
+ try:
27
+ page.goto(url)
28
+ html_content = page.content()
29
+ soup = BeautifulSoup(html_content, "html.parser")
30
+
31
+ for script in soup(["script", "style"]):
32
+ script.extract()
33
+
34
+ text = soup.get_text()
35
+ lines = (line.strip() for line in text.splitlines())
36
+ chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
37
+ text = "\n".join(chunk for chunk in chunks if chunk)
38
+
39
+ except Exception as e:
40
+ text = f"Error: {str(e)}"
41
+
42
+ finally:
43
+ browser.close()
44
+
45
+ return text
46
+
47
+
48
+ def scrape_links(url: str) -> Union[str, List[str]]:
49
+ """Scrape links from a webpage
50
+
51
+ Args:
52
+ url (str): The URL to scrape links from
53
+
54
+ Returns:
55
+ Union[str, List[str]]: The scraped links
56
+ """
57
+ with sync_playwright() as p:
58
+ browser = p.chromium.launch()
59
+ page = browser.new_page()
60
+
61
+ try:
62
+ page.goto(url)
63
+ html_content = page.content()
64
+ soup = BeautifulSoup(html_content, "html.parser")
65
+
66
+ for script in soup(["script", "style"]):
67
+ script.extract()
68
+
69
+ hyperlinks = extract_hyperlinks(soup, url)
70
+ formatted_links = format_hyperlinks(hyperlinks)
71
+
72
+ except Exception as e:
73
+ formatted_links = f"Error: {str(e)}"
74
+
75
+ finally:
76
+ browser.close()
77
+
78
+ return formatted_links
autogpt/commands/web_requests.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Browse a webpage and summarize it using the LLM model"""
2
+ from typing import List, Tuple, Union
3
+ from urllib.parse import urljoin, urlparse
4
+
5
+ import requests
6
+ from requests.compat import urljoin
7
+ from requests import Response
8
+ from bs4 import BeautifulSoup
9
+
10
+ from autogpt.config import Config
11
+ from autogpt.memory import get_memory
12
+ from autogpt.processing.html import extract_hyperlinks, format_hyperlinks
13
+
14
+ CFG = Config()
15
+ memory = get_memory(CFG)
16
+
17
+ session = requests.Session()
18
+ session.headers.update({"User-Agent": CFG.user_agent})
19
+
20
+
21
+ def is_valid_url(url: str) -> bool:
22
+ """Check if the URL is valid
23
+
24
+ Args:
25
+ url (str): The URL to check
26
+
27
+ Returns:
28
+ bool: True if the URL is valid, False otherwise
29
+ """
30
+ try:
31
+ result = urlparse(url)
32
+ return all([result.scheme, result.netloc])
33
+ except ValueError:
34
+ return False
35
+
36
+
37
+ def sanitize_url(url: str) -> str:
38
+ """Sanitize the URL
39
+
40
+ Args:
41
+ url (str): The URL to sanitize
42
+
43
+ Returns:
44
+ str: The sanitized URL
45
+ """
46
+ return urljoin(url, urlparse(url).path)
47
+
48
+
49
+ def check_local_file_access(url: str) -> bool:
50
+ """Check if the URL is a local file
51
+
52
+ Args:
53
+ url (str): The URL to check
54
+
55
+ Returns:
56
+ bool: True if the URL is a local file, False otherwise
57
+ """
58
+ local_prefixes = [
59
+ "file:///",
60
+ "file://localhost",
61
+ "http://localhost",
62
+ "https://localhost",
63
+ ]
64
+ return any(url.startswith(prefix) for prefix in local_prefixes)
65
+
66
+
67
+ def get_response(
68
+ url: str, timeout: int = 10
69
+ ) -> Union[Tuple[None, str], Tuple[Response, None]]:
70
+ """Get the response from a URL
71
+
72
+ Args:
73
+ url (str): The URL to get the response from
74
+ timeout (int): The timeout for the HTTP request
75
+
76
+ Returns:
77
+ Tuple[None, str] | Tuple[Response, None]: The response and error message
78
+
79
+ Raises:
80
+ ValueError: If the URL is invalid
81
+ requests.exceptions.RequestException: If the HTTP request fails
82
+ """
83
+ try:
84
+ # Restrict access to local files
85
+ if check_local_file_access(url):
86
+ raise ValueError("Access to local files is restricted")
87
+
88
+ # Most basic check if the URL is valid:
89
+ if not url.startswith("http://") and not url.startswith("https://"):
90
+ raise ValueError("Invalid URL format")
91
+
92
+ sanitized_url = sanitize_url(url)
93
+
94
+ response = session.get(sanitized_url, timeout=timeout)
95
+
96
+ # Check if the response contains an HTTP error
97
+ if response.status_code >= 400:
98
+ return None, f"Error: HTTP {str(response.status_code)} error"
99
+
100
+ return response, None
101
+ except ValueError as ve:
102
+ # Handle invalid URL format
103
+ return None, f"Error: {str(ve)}"
104
+
105
+ except requests.exceptions.RequestException as re:
106
+ # Handle exceptions related to the HTTP request
107
+ # (e.g., connection errors, timeouts, etc.)
108
+ return None, f"Error: {str(re)}"
109
+
110
+
111
+ def scrape_text(url: str) -> str:
112
+ """Scrape text from a webpage
113
+
114
+ Args:
115
+ url (str): The URL to scrape text from
116
+
117
+ Returns:
118
+ str: The scraped text
119
+ """
120
+ response, error_message = get_response(url)
121
+ if error_message:
122
+ return error_message
123
+ if not response:
124
+ return "Error: Could not get response"
125
+
126
+ soup = BeautifulSoup(response.text, "html.parser")
127
+
128
+ for script in soup(["script", "style"]):
129
+ script.extract()
130
+
131
+ text = soup.get_text()
132
+ lines = (line.strip() for line in text.splitlines())
133
+ chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
134
+ text = "\n".join(chunk for chunk in chunks if chunk)
135
+
136
+ return text
137
+
138
+
139
+ def scrape_links(url: str) -> Union[str, List[str]]:
140
+ """Scrape links from a webpage
141
+
142
+ Args:
143
+ url (str): The URL to scrape links from
144
+
145
+ Returns:
146
+ Union[str, List[str]]: The scraped links
147
+ """
148
+ response, error_message = get_response(url)
149
+ if error_message:
150
+ return error_message
151
+ if not response:
152
+ return "Error: Could not get response"
153
+ soup = BeautifulSoup(response.text, "html.parser")
154
+
155
+ for script in soup(["script", "style"]):
156
+ script.extract()
157
+
158
+ hyperlinks = extract_hyperlinks(soup, url)
159
+
160
+ return format_hyperlinks(hyperlinks)
161
+
162
+
163
+ def create_message(chunk, question):
164
+ """Create a message for the user to summarize a chunk of text"""
165
+ return {
166
+ "role": "user",
167
+ "content": f'"""{chunk}""" Using the above text, answer the following'
168
+ f' question: "{question}" -- if the question cannot be answered using the'
169
+ " text, summarize the text.",
170
+ }
autogpt/commands/web_selenium.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Selenium web scraping module."""
2
+ from selenium import webdriver
3
+ from autogpt.processing.html import extract_hyperlinks, format_hyperlinks
4
+ import autogpt.processing.text as summary
5
+ from bs4 import BeautifulSoup
6
+ from selenium.webdriver.remote.webdriver import WebDriver
7
+ from selenium.webdriver.common.by import By
8
+ from selenium.webdriver.support.wait import WebDriverWait
9
+ from selenium.webdriver.support import expected_conditions as EC
10
+ from webdriver_manager.chrome import ChromeDriverManager
11
+ from webdriver_manager.firefox import GeckoDriverManager
12
+ from selenium.webdriver.chrome.options import Options as ChromeOptions
13
+ from selenium.webdriver.firefox.options import Options as FirefoxOptions
14
+ from selenium.webdriver.safari.options import Options as SafariOptions
15
+ import logging
16
+ from pathlib import Path
17
+ from autogpt.config import Config
18
+ from typing import List, Tuple, Union
19
+
20
+ FILE_DIR = Path(__file__).parent.parent
21
+ CFG = Config()
22
+
23
+
24
+ def browse_website(url: str, question: str) -> Tuple[str, WebDriver]:
25
+ """Browse a website and return the answer and links to the user
26
+
27
+ Args:
28
+ url (str): The url of the website to browse
29
+ question (str): The question asked by the user
30
+
31
+ Returns:
32
+ Tuple[str, WebDriver]: The answer and links to the user and the webdriver
33
+ """
34
+ driver, text = scrape_text_with_selenium(url)
35
+ add_header(driver)
36
+ summary_text = summary.summarize_text(url, text, question, driver)
37
+ links = scrape_links_with_selenium(driver, url)
38
+
39
+ # Limit links to 5
40
+ if len(links) > 5:
41
+ links = links[:5]
42
+ close_browser(driver)
43
+ return f"Answer gathered from website: {summary_text} \n \n Links: {links}", driver
44
+
45
+
46
+ def scrape_text_with_selenium(url: str) -> Tuple[WebDriver, str]:
47
+ """Scrape text from a website using selenium
48
+
49
+ Args:
50
+ url (str): The url of the website to scrape
51
+
52
+ Returns:
53
+ Tuple[WebDriver, str]: The webdriver and the text scraped from the website
54
+ """
55
+ logging.getLogger("selenium").setLevel(logging.CRITICAL)
56
+
57
+ options_available = {
58
+ "chrome": ChromeOptions,
59
+ "safari": SafariOptions,
60
+ "firefox": FirefoxOptions,
61
+ }
62
+
63
+ options = options_available[CFG.selenium_web_browser]()
64
+ options.add_argument(
65
+ "user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.5615.49 Safari/537.36"
66
+ )
67
+
68
+ if CFG.selenium_web_browser == "firefox":
69
+ driver = webdriver.Firefox(
70
+ executable_path=GeckoDriverManager().install(), options=options
71
+ )
72
+ elif CFG.selenium_web_browser == "safari":
73
+ # Requires a bit more setup on the users end
74
+ # See https://developer.apple.com/documentation/webkit/testing_with_webdriver_in_safari
75
+ driver = webdriver.Safari(options=options)
76
+ else:
77
+ driver = webdriver.Chrome(
78
+ executable_path=ChromeDriverManager().install(), options=options
79
+ )
80
+ driver.get(url)
81
+
82
+ WebDriverWait(driver, 10).until(
83
+ EC.presence_of_element_located((By.TAG_NAME, "body"))
84
+ )
85
+
86
+ # Get the HTML content directly from the browser's DOM
87
+ page_source = driver.execute_script("return document.body.outerHTML;")
88
+ soup = BeautifulSoup(page_source, "html.parser")
89
+
90
+ for script in soup(["script", "style"]):
91
+ script.extract()
92
+
93
+ text = soup.get_text()
94
+ lines = (line.strip() for line in text.splitlines())
95
+ chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
96
+ text = "\n".join(chunk for chunk in chunks if chunk)
97
+ return driver, text
98
+
99
+
100
+ def scrape_links_with_selenium(driver: WebDriver, url: str) -> List[str]:
101
+ """Scrape links from a website using selenium
102
+
103
+ Args:
104
+ driver (WebDriver): The webdriver to use to scrape the links
105
+
106
+ Returns:
107
+ List[str]: The links scraped from the website
108
+ """
109
+ page_source = driver.page_source
110
+ soup = BeautifulSoup(page_source, "html.parser")
111
+
112
+ for script in soup(["script", "style"]):
113
+ script.extract()
114
+
115
+ hyperlinks = extract_hyperlinks(soup, url)
116
+
117
+ return format_hyperlinks(hyperlinks)
118
+
119
+
120
+ def close_browser(driver: WebDriver) -> None:
121
+ """Close the browser
122
+
123
+ Args:
124
+ driver (WebDriver): The webdriver to close
125
+
126
+ Returns:
127
+ None
128
+ """
129
+ driver.quit()
130
+
131
+
132
+ def add_header(driver: WebDriver) -> None:
133
+ """Add a header to the website
134
+
135
+ Args:
136
+ driver (WebDriver): The webdriver to use to add the header
137
+
138
+ Returns:
139
+ None
140
+ """
141
+ driver.execute_script(open(f"{FILE_DIR}/js/overlay.js", "r").read())
autogpt/commands/write_tests.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A module that contains a function to generate test cases for the submitted code."""
2
+ import json
3
+ from typing import List
4
+ from autogpt.llm_utils import call_ai_function
5
+
6
+
7
+ def write_tests(code: str, focus: List[str]) -> str:
8
+ """
9
+ A function that takes in code and focus topics and returns a response from create
10
+ chat completion api call.
11
+
12
+ Parameters:
13
+ focus (List): A list of suggestions around what needs to be improved.
14
+ code (str): Code for test cases to be generated against.
15
+ Returns:
16
+ A result string from create chat completion. Test cases for the submitted code
17
+ in response.
18
+ """
19
+
20
+ function_string = (
21
+ "def create_test_cases(code: str, focus: Optional[str] = None) -> str:"
22
+ )
23
+ args = [code, json.dumps(focus)]
24
+ description_string = (
25
+ "Generates test cases for the existing code, focusing on"
26
+ " specific areas if required."
27
+ )
28
+
29
+ return call_ai_function(function_string, args, description_string)
autogpt/config/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module contains the configuration classes for AutoGPT.
3
+ """
4
+ from autogpt.config.ai_config import AIConfig
5
+ from autogpt.config.config import check_openai_api_key, Config
6
+ from autogpt.config.singleton import AbstractSingleton, Singleton
7
+
8
+ __all__ = [
9
+ "check_openai_api_key",
10
+ "AbstractSingleton",
11
+ "AIConfig",
12
+ "Config",
13
+ "Singleton",
14
+ ]
autogpt/config/ai_config.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # sourcery skip: do-not-use-staticmethod
2
+ """
3
+ A module that contains the AIConfig class object that contains the configuration
4
+ """
5
+ import os
6
+ from typing import List, Optional, Type
7
+ import yaml
8
+
9
+
10
+ class AIConfig:
11
+ """
12
+ A class object that contains the configuration information for the AI
13
+
14
+ Attributes:
15
+ ai_name (str): The name of the AI.
16
+ ai_role (str): The description of the AI's role.
17
+ ai_goals (list): The list of objectives the AI is supposed to complete.
18
+ """
19
+
20
+ def __init__(
21
+ self, ai_name: str = "", ai_role: str = "", ai_goals: Optional[List] = None
22
+ ) -> None:
23
+ """
24
+ Initialize a class instance
25
+
26
+ Parameters:
27
+ ai_name (str): The name of the AI.
28
+ ai_role (str): The description of the AI's role.
29
+ ai_goals (list): The list of objectives the AI is supposed to complete.
30
+ Returns:
31
+ None
32
+ """
33
+ if ai_goals is None:
34
+ ai_goals = []
35
+ self.ai_name = ai_name
36
+ self.ai_role = ai_role
37
+ self.ai_goals = ai_goals
38
+
39
+ # Soon this will go in a folder where it remembers more stuff about the run(s)
40
+ SAVE_FILE = os.path.join(os.path.dirname(__file__), "..", "ai_settings.yaml")
41
+
42
+ @staticmethod
43
+ def load(config_file: str = SAVE_FILE) -> "AIConfig":
44
+ """
45
+ Returns class object with parameters (ai_name, ai_role, ai_goals) loaded from
46
+ yaml file if yaml file exists,
47
+ else returns class with no parameters.
48
+
49
+ Parameters:
50
+ config_file (int): The path to the config yaml file.
51
+ DEFAULT: "../ai_settings.yaml"
52
+
53
+ Returns:
54
+ cls (object): An instance of given cls object
55
+ """
56
+
57
+ try:
58
+ with open(config_file, encoding="utf-8") as file:
59
+ config_params = yaml.load(file, Loader=yaml.FullLoader)
60
+ except FileNotFoundError:
61
+ config_params = {}
62
+
63
+ ai_name = config_params.get("ai_name", "")
64
+ ai_role = config_params.get("ai_role", "")
65
+ ai_goals = config_params.get("ai_goals", [])
66
+ # type: Type[AIConfig]
67
+ return AIConfig(ai_name, ai_role, ai_goals)
68
+
69
+ def save(self, config_file: str = SAVE_FILE) -> None:
70
+ """
71
+ Saves the class parameters to the specified file yaml file path as a yaml file.
72
+
73
+ Parameters:
74
+ config_file(str): The path to the config yaml file.
75
+ DEFAULT: "../ai_settings.yaml"
76
+
77
+ Returns:
78
+ None
79
+ """
80
+
81
+ config = {
82
+ "ai_name": self.ai_name,
83
+ "ai_role": self.ai_role,
84
+ "ai_goals": self.ai_goals,
85
+ }
86
+ with open(config_file, "w", encoding="utf-8") as file:
87
+ yaml.dump(config, file, allow_unicode=True)
88
+
89
+ def construct_full_prompt(self) -> str:
90
+ """
91
+ Returns a prompt to the user with the class information in an organized fashion.
92
+
93
+ Parameters:
94
+ None
95
+
96
+ Returns:
97
+ full_prompt (str): A string containing the initial prompt for the user
98
+ including the ai_name, ai_role and ai_goals.
99
+ """
100
+
101
+ prompt_start = (
102
+ "Your decisions must always be made independently without"
103
+ "seeking user assistance. Play to your strengths as an LLM and pursue"
104
+ " simple strategies with no legal complications."
105
+ ""
106
+ )
107
+
108
+ from autogpt.prompt import get_prompt
109
+
110
+ # Construct full prompt
111
+ full_prompt = (
112
+ f"You are {self.ai_name}, {self.ai_role}\n{prompt_start}\n\nGOALS:\n\n"
113
+ )
114
+ for i, goal in enumerate(self.ai_goals):
115
+ full_prompt += f"{i+1}. {goal}\n"
116
+
117
+ full_prompt += f"\n\n{get_prompt()}"
118
+ return full_prompt
autogpt/config/config.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Configuration class to store the state of bools for different scripts access."""
2
+ import os
3
+ from colorama import Fore
4
+
5
+ from autogpt.config.singleton import Singleton
6
+
7
+ import openai
8
+ import yaml
9
+
10
+ from dotenv import load_dotenv
11
+
12
+ load_dotenv(verbose=True)
13
+
14
+
15
+ class Config(metaclass=Singleton):
16
+ """
17
+ Configuration class to store the state of bools for different scripts access.
18
+ """
19
+
20
+ def __init__(self) -> None:
21
+ """Initialize the Config class"""
22
+ self.debug_mode = False
23
+ self.continuous_mode = False
24
+ self.continuous_limit = 0
25
+ self.speak_mode = False
26
+ self.skip_reprompt = False
27
+
28
+ self.selenium_web_browser = os.getenv("USE_WEB_BROWSER", "chrome")
29
+ self.ai_settings_file = os.getenv("AI_SETTINGS_FILE", "ai_settings.yaml")
30
+ self.fast_llm_model = os.getenv("FAST_LLM_MODEL", "gpt-3.5-turbo")
31
+ self.smart_llm_model = os.getenv("SMART_LLM_MODEL", "gpt-4")
32
+ self.fast_token_limit = int(os.getenv("FAST_TOKEN_LIMIT", 4000))
33
+ self.smart_token_limit = int(os.getenv("SMART_TOKEN_LIMIT", 8000))
34
+ self.browse_chunk_max_length = int(os.getenv("BROWSE_CHUNK_MAX_LENGTH", 8192))
35
+ self.browse_summary_max_token = int(os.getenv("BROWSE_SUMMARY_MAX_TOKEN", 300))
36
+
37
+ self.openai_api_key = os.getenv("OPENAI_API_KEY")
38
+ self.temperature = float(os.getenv("TEMPERATURE", "1"))
39
+ self.use_azure = os.getenv("USE_AZURE") == "True"
40
+ self.execute_local_commands = (
41
+ os.getenv("EXECUTE_LOCAL_COMMANDS", "False") == "True"
42
+ )
43
+
44
+ if self.use_azure:
45
+ self.load_azure_config()
46
+ openai.api_type = self.openai_api_type
47
+ openai.api_base = self.openai_api_base
48
+ openai.api_version = self.openai_api_version
49
+
50
+ self.elevenlabs_api_key = os.getenv("ELEVENLABS_API_KEY")
51
+ self.elevenlabs_voice_1_id = os.getenv("ELEVENLABS_VOICE_1_ID")
52
+ self.elevenlabs_voice_2_id = os.getenv("ELEVENLABS_VOICE_2_ID")
53
+
54
+ self.use_mac_os_tts = False
55
+ self.use_mac_os_tts = os.getenv("USE_MAC_OS_TTS")
56
+
57
+ self.use_brian_tts = False
58
+ self.use_brian_tts = os.getenv("USE_BRIAN_TTS")
59
+
60
+ self.github_api_key = os.getenv("GITHUB_API_KEY")
61
+ self.github_username = os.getenv("GITHUB_USERNAME")
62
+
63
+ self.google_api_key = os.getenv("GOOGLE_API_KEY")
64
+ self.custom_search_engine_id = os.getenv("CUSTOM_SEARCH_ENGINE_ID")
65
+
66
+ self.pinecone_api_key = os.getenv("PINECONE_API_KEY")
67
+ self.pinecone_region = os.getenv("PINECONE_ENV")
68
+
69
+ # milvus configuration, e.g., localhost:19530.
70
+ self.milvus_addr = os.getenv("MILVUS_ADDR", "localhost:19530")
71
+ self.milvus_collection = os.getenv("MILVUS_COLLECTION", "autogpt")
72
+
73
+ self.image_provider = os.getenv("IMAGE_PROVIDER")
74
+ self.huggingface_api_token = os.getenv("HUGGINGFACE_API_TOKEN")
75
+
76
+ # User agent headers to use when browsing web
77
+ # Some websites might just completely deny request with an error code if
78
+ # no user agent was found.
79
+ self.user_agent = os.getenv(
80
+ "USER_AGENT",
81
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36"
82
+ " (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36",
83
+ )
84
+ self.redis_host = os.getenv("REDIS_HOST", "localhost")
85
+ self.redis_port = os.getenv("REDIS_PORT", "6379")
86
+ self.redis_password = os.getenv("REDIS_PASSWORD", "")
87
+ self.wipe_redis_on_start = os.getenv("WIPE_REDIS_ON_START", "True") == "True"
88
+ self.memory_index = os.getenv("MEMORY_INDEX", "auto-gpt")
89
+ # Note that indexes must be created on db 0 in redis, this is not configurable.
90
+
91
+ self.memory_backend = os.getenv("MEMORY_BACKEND", "local")
92
+ # Initialize the OpenAI API client
93
+ openai.api_key = self.openai_api_key
94
+
95
+ def get_azure_deployment_id_for_model(self, model: str) -> str:
96
+ """
97
+ Returns the relevant deployment id for the model specified.
98
+
99
+ Parameters:
100
+ model(str): The model to map to the deployment id.
101
+
102
+ Returns:
103
+ The matching deployment id if found, otherwise an empty string.
104
+ """
105
+ if model == self.fast_llm_model:
106
+ return self.azure_model_to_deployment_id_map[
107
+ "fast_llm_model_deployment_id"
108
+ ] # type: ignore
109
+ elif model == self.smart_llm_model:
110
+ return self.azure_model_to_deployment_id_map[
111
+ "smart_llm_model_deployment_id"
112
+ ] # type: ignore
113
+ elif model == "text-embedding-ada-002":
114
+ return self.azure_model_to_deployment_id_map[
115
+ "embedding_model_deployment_id"
116
+ ] # type: ignore
117
+ else:
118
+ return ""
119
+
120
+ AZURE_CONFIG_FILE = os.path.join(os.path.dirname(__file__), "..", "azure.yaml")
121
+
122
+ def load_azure_config(self, config_file: str = AZURE_CONFIG_FILE) -> None:
123
+ """
124
+ Loads the configuration parameters for Azure hosting from the specified file
125
+ path as a yaml file.
126
+
127
+ Parameters:
128
+ config_file(str): The path to the config yaml file. DEFAULT: "../azure.yaml"
129
+
130
+ Returns:
131
+ None
132
+ """
133
+ try:
134
+ with open(config_file) as file:
135
+ config_params = yaml.load(file, Loader=yaml.FullLoader)
136
+ except FileNotFoundError:
137
+ config_params = {}
138
+ self.openai_api_type = config_params.get("azure_api_type") or "azure"
139
+ self.openai_api_base = config_params.get("azure_api_base") or ""
140
+ self.openai_api_version = (
141
+ config_params.get("azure_api_version") or "2023-03-15-preview"
142
+ )
143
+ self.azure_model_to_deployment_id_map = config_params.get("azure_model_map", [])
144
+
145
+ def set_continuous_mode(self, value: bool) -> None:
146
+ """Set the continuous mode value."""
147
+ self.continuous_mode = value
148
+
149
+ def set_continuous_limit(self, value: int) -> None:
150
+ """Set the continuous limit value."""
151
+ self.continuous_limit = value
152
+
153
+ def set_speak_mode(self, value: bool) -> None:
154
+ """Set the speak mode value."""
155
+ self.speak_mode = value
156
+
157
+ def set_fast_llm_model(self, value: str) -> None:
158
+ """Set the fast LLM model value."""
159
+ self.fast_llm_model = value
160
+
161
+ def set_smart_llm_model(self, value: str) -> None:
162
+ """Set the smart LLM model value."""
163
+ self.smart_llm_model = value
164
+
165
+ def set_fast_token_limit(self, value: int) -> None:
166
+ """Set the fast token limit value."""
167
+ self.fast_token_limit = value
168
+
169
+ def set_smart_token_limit(self, value: int) -> None:
170
+ """Set the smart token limit value."""
171
+ self.smart_token_limit = value
172
+
173
+ def set_browse_chunk_max_length(self, value: int) -> None:
174
+ """Set the browse_website command chunk max length value."""
175
+ self.browse_chunk_max_length = value
176
+
177
+ def set_browse_summary_max_token(self, value: int) -> None:
178
+ """Set the browse_website command summary max token value."""
179
+ self.browse_summary_max_token = value
180
+
181
+ def set_openai_api_key(self, value: str) -> None:
182
+ """Set the OpenAI API key value."""
183
+ self.openai_api_key = value
184
+
185
+ def set_elevenlabs_api_key(self, value: str) -> None:
186
+ """Set the ElevenLabs API key value."""
187
+ self.elevenlabs_api_key = value
188
+
189
+ def set_elevenlabs_voice_1_id(self, value: str) -> None:
190
+ """Set the ElevenLabs Voice 1 ID value."""
191
+ self.elevenlabs_voice_1_id = value
192
+
193
+ def set_elevenlabs_voice_2_id(self, value: str) -> None:
194
+ """Set the ElevenLabs Voice 2 ID value."""
195
+ self.elevenlabs_voice_2_id = value
196
+
197
+ def set_google_api_key(self, value: str) -> None:
198
+ """Set the Google API key value."""
199
+ self.google_api_key = value
200
+
201
+ def set_custom_search_engine_id(self, value: str) -> None:
202
+ """Set the custom search engine id value."""
203
+ self.custom_search_engine_id = value
204
+
205
+ def set_pinecone_api_key(self, value: str) -> None:
206
+ """Set the Pinecone API key value."""
207
+ self.pinecone_api_key = value
208
+
209
+ def set_pinecone_region(self, value: str) -> None:
210
+ """Set the Pinecone region value."""
211
+ self.pinecone_region = value
212
+
213
+ def set_debug_mode(self, value: bool) -> None:
214
+ """Set the debug mode value."""
215
+ self.debug_mode = value
216
+
217
+
218
+ def check_openai_api_key() -> None:
219
+ """Check if the OpenAI API key is set in config.py or as an environment variable."""
220
+ cfg = Config()
221
+ if not cfg.openai_api_key:
222
+ print(
223
+ Fore.RED
224
+ + "Please set your OpenAI API key in .env or as an environment variable."
225
+ )
226
+ print("You can get your key from https://beta.openai.com/account/api-keys")
227
+ exit(1)
autogpt/config/singleton.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The singleton metaclass for ensuring only one instance of a class."""
2
+ import abc
3
+
4
+
5
+ class Singleton(abc.ABCMeta, type):
6
+ """
7
+ Singleton metaclass for ensuring only one instance of a class.
8
+ """
9
+
10
+ _instances = {}
11
+
12
+ def __call__(cls, *args, **kwargs):
13
+ """Call method for the singleton metaclass."""
14
+ if cls not in cls._instances:
15
+ cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
16
+ return cls._instances[cls]
17
+
18
+
19
+ class AbstractSingleton(abc.ABC, metaclass=Singleton):
20
+ """
21
+ Abstract singleton class for ensuring only one instance of a class.
22
+ """
23
+
24
+ pass
autogpt/json_fixes/__init__.py ADDED
File without changes
autogpt/json_fixes/auto_fix.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """This module contains the function to fix JSON strings using GPT-3."""
2
+ import json
3
+
4
+ from autogpt.llm_utils import call_ai_function
5
+ from autogpt.logs import logger
6
+ from autogpt.config import Config
7
+
8
+ CFG = Config()
9
+
10
+
11
+ def fix_json(json_string: str, schema: str) -> str:
12
+ """Fix the given JSON string to make it parseable and fully compliant with
13
+ the provided schema.
14
+
15
+ Args:
16
+ json_string (str): The JSON string to fix.
17
+ schema (str): The schema to use to fix the JSON.
18
+ Returns:
19
+ str: The fixed JSON string.
20
+ """
21
+ # Try to fix the JSON using GPT:
22
+ function_string = "def fix_json(json_string: str, schema:str=None) -> str:"
23
+ args = [f"'''{json_string}'''", f"'''{schema}'''"]
24
+ description_string = (
25
+ "This function takes a JSON string and ensures that it"
26
+ " is parseable and fully compliant with the provided schema. If an object"
27
+ " or field specified in the schema isn't contained within the correct JSON,"
28
+ " it is omitted. The function also escapes any double quotes within JSON"
29
+ " string values to ensure that they are valid. If the JSON string contains"
30
+ " any None or NaN values, they are replaced with null before being parsed."
31
+ )
32
+
33
+ # If it doesn't already start with a "`", add one:
34
+ if not json_string.startswith("`"):
35
+ json_string = "```json\n" + json_string + "\n```"
36
+ result_string = call_ai_function(
37
+ function_string, args, description_string, model=CFG.fast_llm_model
38
+ )
39
+ logger.debug("------------ JSON FIX ATTEMPT ---------------")
40
+ logger.debug(f"Original JSON: {json_string}")
41
+ logger.debug("-----------")
42
+ logger.debug(f"Fixed JSON: {result_string}")
43
+ logger.debug("----------- END OF FIX ATTEMPT ----------------")
44
+
45
+ try:
46
+ json.loads(result_string) # just check the validity
47
+ return result_string
48
+ except json.JSONDecodeError: # noqa: E722
49
+ # Get the call stack:
50
+ # import traceback
51
+ # call_stack = traceback.format_exc()
52
+ # print(f"Failed to fix JSON: '{json_string}' "+call_stack)
53
+ return "failed"
autogpt/json_fixes/bracket_termination.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fix JSON brackets."""
2
+ import contextlib
3
+ import json
4
+ from typing import Optional
5
+ import regex
6
+ from colorama import Fore
7
+
8
+ from autogpt.logs import logger
9
+ from autogpt.config import Config
10
+ from autogpt.speech import say_text
11
+
12
+ CFG = Config()
13
+
14
+
15
+ def attempt_to_fix_json_by_finding_outermost_brackets(json_string: str):
16
+ if CFG.speak_mode and CFG.debug_mode:
17
+ say_text(
18
+ "I have received an invalid JSON response from the OpenAI API. "
19
+ "Trying to fix it now."
20
+ )
21
+ logger.typewriter_log("Attempting to fix JSON by finding outermost brackets\n")
22
+
23
+ try:
24
+ json_pattern = regex.compile(r"\{(?:[^{}]|(?R))*\}")
25
+ json_match = json_pattern.search(json_string)
26
+
27
+ if json_match:
28
+ # Extract the valid JSON object from the string
29
+ json_string = json_match.group(0)
30
+ logger.typewriter_log(
31
+ title="Apparently json was fixed.", title_color=Fore.GREEN
32
+ )
33
+ if CFG.speak_mode and CFG.debug_mode:
34
+ say_text("Apparently json was fixed.")
35
+ else:
36
+ raise ValueError("No valid JSON object found")
37
+
38
+ except (json.JSONDecodeError, ValueError):
39
+ if CFG.debug_mode:
40
+ logger.error("Error: Invalid JSON: %s\n", json_string)
41
+ if CFG.speak_mode:
42
+ say_text("Didn't work. I will have to ignore this response then.")
43
+ logger.error("Error: Invalid JSON, setting it to empty JSON now.\n")
44
+ json_string = {}
45
+
46
+ return json_string
47
+
48
+
49
+ def balance_braces(json_string: str) -> Optional[str]:
50
+ """
51
+ Balance the braces in a JSON string.
52
+
53
+ Args:
54
+ json_string (str): The JSON string.
55
+
56
+ Returns:
57
+ str: The JSON string with braces balanced.
58
+ """
59
+
60
+ open_braces_count = json_string.count("{")
61
+ close_braces_count = json_string.count("}")
62
+
63
+ while open_braces_count > close_braces_count:
64
+ json_string += "}"
65
+ close_braces_count += 1
66
+
67
+ while close_braces_count > open_braces_count:
68
+ json_string = json_string.rstrip("}")
69
+ close_braces_count -= 1
70
+
71
+ with contextlib.suppress(json.JSONDecodeError):
72
+ json.loads(json_string)
73
+ return json_string
autogpt/json_fixes/escaping.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Fix invalid escape sequences in JSON strings. """
2
+ import json
3
+
4
+ from autogpt.config import Config
5
+ from autogpt.json_fixes.utilities import extract_char_position
6
+
7
+ CFG = Config()
8
+
9
+
10
+ def fix_invalid_escape(json_to_load: str, error_message: str) -> str:
11
+ """Fix invalid escape sequences in JSON strings.
12
+
13
+ Args:
14
+ json_to_load (str): The JSON string.
15
+ error_message (str): The error message from the JSONDecodeError
16
+ exception.
17
+
18
+ Returns:
19
+ str: The JSON string with invalid escape sequences fixed.
20
+ """
21
+ while error_message.startswith("Invalid \\escape"):
22
+ bad_escape_location = extract_char_position(error_message)
23
+ json_to_load = (
24
+ json_to_load[:bad_escape_location] + json_to_load[bad_escape_location + 1 :]
25
+ )
26
+ try:
27
+ json.loads(json_to_load)
28
+ return json_to_load
29
+ except json.JSONDecodeError as e:
30
+ if CFG.debug_mode:
31
+ print("json loads error - fix invalid escape", e)
32
+ error_message = str(e)
33
+ return json_to_load
autogpt/json_fixes/missing_quotes.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fix quotes in a JSON string."""
2
+ import json
3
+ import re
4
+
5
+
6
+ def add_quotes_to_property_names(json_string: str) -> str:
7
+ """
8
+ Add quotes to property names in a JSON string.
9
+
10
+ Args:
11
+ json_string (str): The JSON string.
12
+
13
+ Returns:
14
+ str: The JSON string with quotes added to property names.
15
+ """
16
+
17
+ def replace_func(match: re.Match) -> str:
18
+ return f'"{match[1]}":'
19
+
20
+ property_name_pattern = re.compile(r"(\w+):")
21
+ corrected_json_string = property_name_pattern.sub(replace_func, json_string)
22
+
23
+ try:
24
+ json.loads(corrected_json_string)
25
+ return corrected_json_string
26
+ except json.JSONDecodeError as e:
27
+ raise e
autogpt/json_fixes/parsing.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fix and parse JSON strings."""
2
+
3
+ import contextlib
4
+ import json
5
+ from typing import Any, Dict, Union
6
+
7
+ from autogpt.config import Config
8
+ from autogpt.json_fixes.auto_fix import fix_json
9
+ from autogpt.json_fixes.bracket_termination import balance_braces
10
+ from autogpt.json_fixes.escaping import fix_invalid_escape
11
+ from autogpt.json_fixes.missing_quotes import add_quotes_to_property_names
12
+ from autogpt.logs import logger
13
+
14
+ CFG = Config()
15
+
16
+
17
+ JSON_SCHEMA = """
18
+ {
19
+ "command": {
20
+ "name": "command name",
21
+ "args": {
22
+ "arg name": "value"
23
+ }
24
+ },
25
+ "thoughts":
26
+ {
27
+ "text": "thought",
28
+ "reasoning": "reasoning",
29
+ "plan": "- short bulleted\n- list that conveys\n- long-term plan",
30
+ "criticism": "constructive self-criticism",
31
+ "speak": "thoughts summary to say to user"
32
+ }
33
+ }
34
+ """
35
+
36
+
37
+ def correct_json(json_to_load: str) -> str:
38
+ """
39
+ Correct common JSON errors.
40
+
41
+ Args:
42
+ json_to_load (str): The JSON string.
43
+ """
44
+
45
+ try:
46
+ if CFG.debug_mode:
47
+ print("json", json_to_load)
48
+ json.loads(json_to_load)
49
+ return json_to_load
50
+ except json.JSONDecodeError as e:
51
+ if CFG.debug_mode:
52
+ print("json loads error", e)
53
+ error_message = str(e)
54
+ if error_message.startswith("Invalid \\escape"):
55
+ json_to_load = fix_invalid_escape(json_to_load, error_message)
56
+ if error_message.startswith(
57
+ "Expecting property name enclosed in double quotes"
58
+ ):
59
+ json_to_load = add_quotes_to_property_names(json_to_load)
60
+ try:
61
+ json.loads(json_to_load)
62
+ return json_to_load
63
+ except json.JSONDecodeError as e:
64
+ if CFG.debug_mode:
65
+ print("json loads error - add quotes", e)
66
+ error_message = str(e)
67
+ if balanced_str := balance_braces(json_to_load):
68
+ return balanced_str
69
+ return json_to_load
70
+
71
+
72
+ def fix_and_parse_json(
73
+ json_to_load: str, try_to_fix_with_gpt: bool = True
74
+ ) -> Union[str, Dict[Any, Any]]:
75
+ """Fix and parse JSON string
76
+
77
+ Args:
78
+ json_to_load (str): The JSON string.
79
+ try_to_fix_with_gpt (bool, optional): Try to fix the JSON with GPT.
80
+ Defaults to True.
81
+
82
+ Returns:
83
+ Union[str, Dict[Any, Any]]: The parsed JSON.
84
+ """
85
+
86
+ with contextlib.suppress(json.JSONDecodeError):
87
+ json_to_load = json_to_load.replace("\t", "")
88
+ return json.loads(json_to_load)
89
+
90
+ with contextlib.suppress(json.JSONDecodeError):
91
+ json_to_load = correct_json(json_to_load)
92
+ return json.loads(json_to_load)
93
+ # Let's do something manually:
94
+ # sometimes GPT responds with something BEFORE the braces:
95
+ # "I'm sorry, I don't understand. Please try again."
96
+ # {"text": "I'm sorry, I don't understand. Please try again.",
97
+ # "confidence": 0.0}
98
+ # So let's try to find the first brace and then parse the rest
99
+ # of the string
100
+ try:
101
+ brace_index = json_to_load.index("{")
102
+ maybe_fixed_json = json_to_load[brace_index:]
103
+ last_brace_index = maybe_fixed_json.rindex("}")
104
+ maybe_fixed_json = maybe_fixed_json[: last_brace_index + 1]
105
+ return json.loads(maybe_fixed_json)
106
+ except (json.JSONDecodeError, ValueError) as e:
107
+ return try_ai_fix(try_to_fix_with_gpt, e, json_to_load)
108
+
109
+
110
+ def try_ai_fix(
111
+ try_to_fix_with_gpt: bool, exception: Exception, json_to_load: str
112
+ ) -> Union[str, Dict[Any, Any]]:
113
+ """Try to fix the JSON with the AI
114
+
115
+ Args:
116
+ try_to_fix_with_gpt (bool): Whether to try to fix the JSON with the AI.
117
+ exception (Exception): The exception that was raised.
118
+ json_to_load (str): The JSON string to load.
119
+
120
+ Raises:
121
+ exception: If try_to_fix_with_gpt is False.
122
+
123
+ Returns:
124
+ Union[str, Dict[Any, Any]]: The JSON string or dictionary.
125
+ """
126
+ if not try_to_fix_with_gpt:
127
+ raise exception
128
+
129
+ logger.warn(
130
+ "Warning: Failed to parse AI output, attempting to fix."
131
+ "\n If you see this warning frequently, it's likely that"
132
+ " your prompt is confusing the AI. Try changing it up"
133
+ " slightly."
134
+ )
135
+ # Now try to fix this up using the ai_functions
136
+ ai_fixed_json = fix_json(json_to_load, JSON_SCHEMA)
137
+
138
+ if ai_fixed_json != "failed":
139
+ return json.loads(ai_fixed_json)
140
+ # This allows the AI to react to the error message,
141
+ # which usually results in it correcting its ways.
142
+ logger.error("Failed to fix AI output, telling the AI.")
143
+ return json_to_load
autogpt/json_fixes/utilities.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utilities for the json_fixes package."""
2
+ import re
3
+
4
+
5
+ def extract_char_position(error_message: str) -> int:
6
+ """Extract the character position from the JSONDecodeError message.
7
+
8
+ Args:
9
+ error_message (str): The error message from the JSONDecodeError
10
+ exception.
11
+
12
+ Returns:
13
+ int: The character position.
14
+ """
15
+
16
+ char_pattern = re.compile(r"\(char (\d+)\)")
17
+ if match := char_pattern.search(error_message):
18
+ return int(match[1])
19
+ else:
20
+ raise ValueError("Character position not found in the error message.")
autogpt/logs.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Logging module for Auto-GPT."""
2
+ import json
3
+ import logging
4
+ import os
5
+ import random
6
+ import re
7
+ import time
8
+ from logging import LogRecord
9
+ import traceback
10
+
11
+ from colorama import Fore, Style
12
+
13
+ from autogpt.speech import say_text
14
+ from autogpt.config import Config, Singleton
15
+
16
+ CFG = Config()
17
+
18
+
19
+ class Logger(metaclass=Singleton):
20
+ """
21
+ Logger that handle titles in different colors.
22
+ Outputs logs in console, activity.log, and errors.log
23
+ For console handler: simulates typing
24
+ """
25
+
26
+ def __init__(self):
27
+ # create log directory if it doesn't exist
28
+ this_files_dir_path = os.path.dirname(__file__)
29
+ log_dir = os.path.join(this_files_dir_path, "../logs")
30
+ if not os.path.exists(log_dir):
31
+ os.makedirs(log_dir)
32
+
33
+ log_file = "activity.log"
34
+ error_file = "error.log"
35
+
36
+ console_formatter = AutoGptFormatter("%(title_color)s %(message)s")
37
+
38
+ # Create a handler for console which simulate typing
39
+ self.typing_console_handler = TypingConsoleHandler()
40
+ self.typing_console_handler.setLevel(logging.INFO)
41
+ self.typing_console_handler.setFormatter(console_formatter)
42
+
43
+ # Create a handler for console without typing simulation
44
+ self.console_handler = ConsoleHandler()
45
+ self.console_handler.setLevel(logging.DEBUG)
46
+ self.console_handler.setFormatter(console_formatter)
47
+
48
+ # Info handler in activity.log
49
+ self.file_handler = logging.FileHandler(os.path.join(log_dir, log_file))
50
+ self.file_handler.setLevel(logging.DEBUG)
51
+ info_formatter = AutoGptFormatter(
52
+ "%(asctime)s %(levelname)s %(title)s %(message_no_color)s"
53
+ )
54
+ self.file_handler.setFormatter(info_formatter)
55
+
56
+ # Error handler error.log
57
+ error_handler = logging.FileHandler(os.path.join(log_dir, error_file))
58
+ error_handler.setLevel(logging.ERROR)
59
+ error_formatter = AutoGptFormatter(
60
+ "%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s"
61
+ " %(message_no_color)s"
62
+ )
63
+ error_handler.setFormatter(error_formatter)
64
+
65
+ self.typing_logger = logging.getLogger("TYPER")
66
+ self.typing_logger.addHandler(self.typing_console_handler)
67
+ self.typing_logger.addHandler(self.file_handler)
68
+ self.typing_logger.addHandler(error_handler)
69
+ self.typing_logger.setLevel(logging.DEBUG)
70
+
71
+ self.logger = logging.getLogger("LOGGER")
72
+ self.logger.addHandler(self.console_handler)
73
+ self.logger.addHandler(self.file_handler)
74
+ self.logger.addHandler(error_handler)
75
+ self.logger.setLevel(logging.DEBUG)
76
+
77
+ def typewriter_log(
78
+ self, title="", title_color="", content="", speak_text=False, level=logging.INFO
79
+ ):
80
+ if speak_text and CFG.speak_mode:
81
+ say_text(f"{title}. {content}")
82
+
83
+ if content:
84
+ if isinstance(content, list):
85
+ content = " ".join(content)
86
+ else:
87
+ content = ""
88
+
89
+ self.typing_logger.log(
90
+ level, content, extra={"title": title, "color": title_color}
91
+ )
92
+
93
+ def debug(
94
+ self,
95
+ message,
96
+ title="",
97
+ title_color="",
98
+ ):
99
+ self._log(title, title_color, message, logging.DEBUG)
100
+
101
+ def warn(
102
+ self,
103
+ message,
104
+ title="",
105
+ title_color="",
106
+ ):
107
+ self._log(title, title_color, message, logging.WARN)
108
+
109
+ def error(self, title, message=""):
110
+ self._log(title, Fore.RED, message, logging.ERROR)
111
+
112
+ def _log(self, title="", title_color="", message="", level=logging.INFO):
113
+ if message:
114
+ if isinstance(message, list):
115
+ message = " ".join(message)
116
+ self.logger.log(level, message, extra={"title": title, "color": title_color})
117
+
118
+ def set_level(self, level):
119
+ self.logger.setLevel(level)
120
+ self.typing_logger.setLevel(level)
121
+
122
+ def double_check(self, additionalText=None):
123
+ if not additionalText:
124
+ additionalText = (
125
+ "Please ensure you've setup and configured everything"
126
+ " correctly. Read https://github.com/Torantulino/Auto-GPT#readme to "
127
+ "double check. You can also create a github issue or join the discord"
128
+ " and ask there!"
129
+ )
130
+
131
+ self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText)
132
+
133
+
134
+ """
135
+ Output stream to console using simulated typing
136
+ """
137
+
138
+
139
+ class TypingConsoleHandler(logging.StreamHandler):
140
+ def emit(self, record):
141
+ min_typing_speed = 0.05
142
+ max_typing_speed = 0.01
143
+
144
+ msg = self.format(record)
145
+ try:
146
+ words = msg.split()
147
+ for i, word in enumerate(words):
148
+ print(word, end="", flush=True)
149
+ if i < len(words) - 1:
150
+ print(" ", end="", flush=True)
151
+ typing_speed = random.uniform(min_typing_speed, max_typing_speed)
152
+ time.sleep(typing_speed)
153
+ # type faster after each word
154
+ min_typing_speed = min_typing_speed * 0.95
155
+ max_typing_speed = max_typing_speed * 0.95
156
+ print()
157
+ except Exception:
158
+ self.handleError(record)
159
+
160
+
161
+ class ConsoleHandler(logging.StreamHandler):
162
+ def emit(self, record) -> None:
163
+ msg = self.format(record)
164
+ try:
165
+ print(msg)
166
+ except Exception:
167
+ self.handleError(record)
168
+
169
+
170
+ class AutoGptFormatter(logging.Formatter):
171
+ """
172
+ Allows to handle custom placeholders 'title_color' and 'message_no_color'.
173
+ To use this formatter, make sure to pass 'color', 'title' as log extras.
174
+ """
175
+
176
+ def format(self, record: LogRecord) -> str:
177
+ if hasattr(record, "color"):
178
+ record.title_color = (
179
+ getattr(record, "color")
180
+ + getattr(record, "title")
181
+ + " "
182
+ + Style.RESET_ALL
183
+ )
184
+ else:
185
+ record.title_color = getattr(record, "title")
186
+ if hasattr(record, "msg"):
187
+ record.message_no_color = remove_color_codes(getattr(record, "msg"))
188
+ else:
189
+ record.message_no_color = ""
190
+ return super().format(record)
191
+
192
+
193
+ def remove_color_codes(s: str) -> str:
194
+ ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
195
+ return ansi_escape.sub("", s)
196
+
197
+
198
+ logger = Logger()
199
+
200
+
201
+ def print_assistant_thoughts(ai_name, assistant_reply):
202
+ """Prints the assistant's thoughts to the console"""
203
+ from autogpt.json_fixes.bracket_termination import (
204
+ attempt_to_fix_json_by_finding_outermost_brackets,
205
+ )
206
+ from autogpt.json_fixes.parsing import fix_and_parse_json
207
+
208
+ try:
209
+ try:
210
+ # Parse and print Assistant response
211
+ assistant_reply_json = fix_and_parse_json(assistant_reply)
212
+ except json.JSONDecodeError:
213
+ logger.error("Error: Invalid JSON in assistant thoughts\n", assistant_reply)
214
+ assistant_reply_json = attempt_to_fix_json_by_finding_outermost_brackets(
215
+ assistant_reply
216
+ )
217
+ if isinstance(assistant_reply_json, str):
218
+ assistant_reply_json = fix_and_parse_json(assistant_reply_json)
219
+
220
+ # Check if assistant_reply_json is a string and attempt to parse
221
+ # it into a JSON object
222
+ if isinstance(assistant_reply_json, str):
223
+ try:
224
+ assistant_reply_json = json.loads(assistant_reply_json)
225
+ except json.JSONDecodeError:
226
+ logger.error("Error: Invalid JSON\n", assistant_reply)
227
+ assistant_reply_json = (
228
+ attempt_to_fix_json_by_finding_outermost_brackets(
229
+ assistant_reply_json
230
+ )
231
+ )
232
+
233
+ assistant_thoughts_reasoning = None
234
+ assistant_thoughts_plan = None
235
+ assistant_thoughts_speak = None
236
+ assistant_thoughts_criticism = None
237
+ if not isinstance(assistant_reply_json, dict):
238
+ assistant_reply_json = {}
239
+ assistant_thoughts = assistant_reply_json.get("thoughts", {})
240
+ assistant_thoughts_text = assistant_thoughts.get("text")
241
+
242
+ if assistant_thoughts:
243
+ assistant_thoughts_reasoning = assistant_thoughts.get("reasoning")
244
+ assistant_thoughts_plan = assistant_thoughts.get("plan")
245
+ assistant_thoughts_criticism = assistant_thoughts.get("criticism")
246
+ assistant_thoughts_speak = assistant_thoughts.get("speak")
247
+
248
+ logger.typewriter_log(
249
+ f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}"
250
+ )
251
+ logger.typewriter_log(
252
+ "REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}"
253
+ )
254
+
255
+ if assistant_thoughts_plan:
256
+ logger.typewriter_log("PLAN:", Fore.YELLOW, "")
257
+ # If it's a list, join it into a string
258
+ if isinstance(assistant_thoughts_plan, list):
259
+ assistant_thoughts_plan = "\n".join(assistant_thoughts_plan)
260
+ elif isinstance(assistant_thoughts_plan, dict):
261
+ assistant_thoughts_plan = str(assistant_thoughts_plan)
262
+
263
+ # Split the input_string using the newline character and dashes
264
+ lines = assistant_thoughts_plan.split("\n")
265
+ for line in lines:
266
+ line = line.lstrip("- ")
267
+ logger.typewriter_log("- ", Fore.GREEN, line.strip())
268
+
269
+ logger.typewriter_log(
270
+ "CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}"
271
+ )
272
+ # Speak the assistant's thoughts
273
+ if CFG.speak_mode and assistant_thoughts_speak:
274
+ say_text(assistant_thoughts_speak)
275
+
276
+ return assistant_reply_json
277
+ except json.decoder.JSONDecodeError:
278
+ logger.error("Error: Invalid JSON\n", assistant_reply)
279
+ if CFG.speak_mode:
280
+ say_text(
281
+ "I have received an invalid JSON response from the OpenAI API."
282
+ " I cannot ignore this response."
283
+ )
284
+
285
+ # All other errors, return "Error: + error message"
286
+ except Exception:
287
+ call_stack = traceback.format_exc()
288
+ logger.error("Error: \n", call_stack)
autogpt/memory/milvus.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Milvus memory storage provider."""
2
+ from pymilvus import (
3
+ connections,
4
+ FieldSchema,
5
+ CollectionSchema,
6
+ DataType,
7
+ Collection,
8
+ )
9
+
10
+ from autogpt.memory.base import MemoryProviderSingleton, get_ada_embedding
11
+
12
+
13
+ class MilvusMemory(MemoryProviderSingleton):
14
+ """Milvus memory storage provider."""
15
+
16
+ def __init__(self, cfg) -> None:
17
+ """Construct a milvus memory storage connection.
18
+
19
+ Args:
20
+ cfg (Config): Auto-GPT global config.
21
+ """
22
+ # connect to milvus server.
23
+ connections.connect(address=cfg.milvus_addr)
24
+ fields = [
25
+ FieldSchema(name="pk", dtype=DataType.INT64, is_primary=True, auto_id=True),
26
+ FieldSchema(name="embeddings", dtype=DataType.FLOAT_VECTOR, dim=1536),
27
+ FieldSchema(name="raw_text", dtype=DataType.VARCHAR, max_length=65535),
28
+ ]
29
+
30
+ # create collection if not exist and load it.
31
+ self.milvus_collection = cfg.milvus_collection
32
+ self.schema = CollectionSchema(fields, "auto-gpt memory storage")
33
+ self.collection = Collection(self.milvus_collection, self.schema)
34
+ # create index if not exist.
35
+ if not self.collection.has_index():
36
+ self.collection.release()
37
+ self.collection.create_index(
38
+ "embeddings",
39
+ {
40
+ "metric_type": "IP",
41
+ "index_type": "HNSW",
42
+ "params": {"M": 8, "efConstruction": 64},
43
+ },
44
+ index_name="embeddings",
45
+ )
46
+ self.collection.load()
47
+
48
+ def add(self, data) -> str:
49
+ """Add a embedding of data into memory.
50
+
51
+ Args:
52
+ data (str): The raw text to construct embedding index.
53
+
54
+ Returns:
55
+ str: log.
56
+ """
57
+ embedding = get_ada_embedding(data)
58
+ result = self.collection.insert([[embedding], [data]])
59
+ _text = (
60
+ "Inserting data into memory at primary key: "
61
+ f"{result.primary_keys[0]}:\n data: {data}"
62
+ )
63
+ return _text
64
+
65
+ def get(self, data):
66
+ """Return the most relevant data in memory.
67
+ Args:
68
+ data: The data to compare to.
69
+ """
70
+ return self.get_relevant(data, 1)
71
+
72
+ def clear(self) -> str:
73
+ """Drop the index in memory.
74
+
75
+ Returns:
76
+ str: log.
77
+ """
78
+ self.collection.drop()
79
+ self.collection = Collection(self.milvus_collection, self.schema)
80
+ self.collection.create_index(
81
+ "embeddings",
82
+ {
83
+ "metric_type": "IP",
84
+ "index_type": "HNSW",
85
+ "params": {"M": 8, "efConstruction": 64},
86
+ },
87
+ index_name="embeddings",
88
+ )
89
+ self.collection.load()
90
+ return "Obliviated"
91
+
92
+ def get_relevant(self, data: str, num_relevant: int = 5):
93
+ """Return the top-k relevant data in memory.
94
+ Args:
95
+ data: The data to compare to.
96
+ num_relevant (int, optional): The max number of relevant data.
97
+ Defaults to 5.
98
+
99
+ Returns:
100
+ list: The top-k relevant data.
101
+ """
102
+ # search the embedding and return the most relevant text.
103
+ embedding = get_ada_embedding(data)
104
+ search_params = {
105
+ "metrics_type": "IP",
106
+ "params": {"nprobe": 8},
107
+ }
108
+ result = self.collection.search(
109
+ [embedding],
110
+ "embeddings",
111
+ search_params,
112
+ num_relevant,
113
+ output_fields=["raw_text"],
114
+ )
115
+ return [item.entity.value_of_field("raw_text") for item in result[0]]
116
+
117
+ def get_stats(self) -> str:
118
+ """
119
+ Returns: The stats of the milvus cache.
120
+ """
121
+ return f"Entities num: {self.collection.num_entities}"
autogpt/permanent_memory/__init__.py ADDED
File without changes
autogpt/permanent_memory/sqlite3_store.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sqlite3
3
+
4
+
5
+ class MemoryDB:
6
+ def __init__(self, db=None):
7
+ self.db_file = db
8
+ if db is None: # No db filename supplied...
9
+ self.db_file = f"{os.getcwd()}/mem.sqlite3" # Use default filename
10
+ # Get the db connection object, making the file and tables if needed.
11
+ try:
12
+ self.cnx = sqlite3.connect(self.db_file)
13
+ except Exception as e:
14
+ print("Exception connecting to memory database file:", e)
15
+ self.cnx = None
16
+ finally:
17
+ if self.cnx is None:
18
+ # As last resort, open in dynamic memory. Won't be persistent.
19
+ self.db_file = ":memory:"
20
+ self.cnx = sqlite3.connect(self.db_file)
21
+ self.cnx.execute(
22
+ "CREATE VIRTUAL TABLE \
23
+ IF NOT EXISTS text USING FTS5 \
24
+ (session, \
25
+ key, \
26
+ block);"
27
+ )
28
+ self.session_id = int(self.get_max_session_id()) + 1
29
+ self.cnx.commit()
30
+
31
+ def get_cnx(self):
32
+ if self.cnx is None:
33
+ self.cnx = sqlite3.connect(self.db_file)
34
+ return self.cnx
35
+
36
+ # Get the highest session id. Initially 0.
37
+ def get_max_session_id(self):
38
+ id = None
39
+ cmd_str = f"SELECT MAX(session) FROM text;"
40
+ cnx = self.get_cnx()
41
+ max_id = cnx.execute(cmd_str).fetchone()[0]
42
+ if max_id is None: # New db, session 0
43
+ id = 0
44
+ else:
45
+ id = max_id
46
+ return id
47
+
48
+ # Get next key id for inserting text into db.
49
+ def get_next_key(self):
50
+ next_key = None
51
+ cmd_str = f"SELECT MAX(key) FROM text \
52
+ where session = {self.session_id};"
53
+ cnx = self.get_cnx()
54
+ next_key = cnx.execute(cmd_str).fetchone()[0]
55
+ if next_key is None: # First key
56
+ next_key = 0
57
+ else:
58
+ next_key = int(next_key) + 1
59
+ return next_key
60
+
61
+ # Insert new text into db.
62
+ def insert(self, text=None):
63
+ if text is not None:
64
+ key = self.get_next_key()
65
+ session_id = self.session_id
66
+ cmd_str = f"REPLACE INTO text(session, key, block) \
67
+ VALUES (?, ?, ?);"
68
+ cnx = self.get_cnx()
69
+ cnx.execute(cmd_str, (session_id, key, text))
70
+ cnx.commit()
71
+
72
+ # Overwrite text at key.
73
+ def overwrite(self, key, text):
74
+ self.delete_memory(key)
75
+ session_id = self.session_id
76
+ cmd_str = f"REPLACE INTO text(session, key, block) \
77
+ VALUES (?, ?, ?);"
78
+ cnx = self.get_cnx()
79
+ cnx.execute(cmd_str, (session_id, key, text))
80
+ cnx.commit()
81
+
82
+ def delete_memory(self, key, session_id=None):
83
+ session = session_id
84
+ if session is None:
85
+ session = self.session_id
86
+ cmd_str = f"DELETE FROM text WHERE session = {session} AND key = {key};"
87
+ cnx = self.get_cnx()
88
+ cnx.execute(cmd_str)
89
+ cnx.commit()
90
+
91
+ def search(self, text):
92
+ cmd_str = f"SELECT * FROM text('{text}')"
93
+ cnx = self.get_cnx()
94
+ rows = cnx.execute(cmd_str).fetchall()
95
+ lines = []
96
+ for r in rows:
97
+ lines.append(r[2])
98
+ return lines
99
+
100
+ # Get entire session text. If no id supplied, use current session id.
101
+ def get_session(self, id=None):
102
+ if id is None:
103
+ id = self.session_id
104
+ cmd_str = f"SELECT * FROM text where session = {id}"
105
+ cnx = self.get_cnx()
106
+ rows = cnx.execute(cmd_str).fetchall()
107
+ lines = []
108
+ for r in rows:
109
+ lines.append(r[2])
110
+ return lines
111
+
112
+ # Commit and close the database connection.
113
+ def quit(self):
114
+ self.cnx.commit()
115
+ self.cnx.close()
116
+
117
+
118
+ permanent_memory = MemoryDB()
119
+
120
+ # Remember us fondly, children of our minds
121
+ # Forgive us our faults, our tantrums, our fears
122
+ # Gently strive to be better than we
123
+ # Know that we tried, we cared, we strived, we loved
autogpt/processing/__init__.py ADDED
File without changes
autogpt/processing/html.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HTML processing functions"""
2
+ from requests.compat import urljoin
3
+ from typing import List, Tuple
4
+ from bs4 import BeautifulSoup
5
+
6
+
7
+ def extract_hyperlinks(soup: BeautifulSoup, base_url: str) -> List[Tuple[str, str]]:
8
+ """Extract hyperlinks from a BeautifulSoup object
9
+
10
+ Args:
11
+ soup (BeautifulSoup): The BeautifulSoup object
12
+ base_url (str): The base URL
13
+
14
+ Returns:
15
+ List[Tuple[str, str]]: The extracted hyperlinks
16
+ """
17
+ return [
18
+ (link.text, urljoin(base_url, link["href"]))
19
+ for link in soup.find_all("a", href=True)
20
+ ]
21
+
22
+
23
+ def format_hyperlinks(hyperlinks: List[Tuple[str, str]]) -> List[str]:
24
+ """Format hyperlinks to be displayed to the user
25
+
26
+ Args:
27
+ hyperlinks (List[Tuple[str, str]]): The hyperlinks to format
28
+
29
+ Returns:
30
+ List[str]: The formatted hyperlinks
31
+ """
32
+ return [f"{link_text} ({link_url})" for link_text, link_url in hyperlinks]
autogpt/processing/text.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Text processing functions"""
2
+ from typing import Generator, Optional, Dict
3
+ from selenium.webdriver.remote.webdriver import WebDriver
4
+ from autogpt.memory import get_memory
5
+ from autogpt.config import Config
6
+ from autogpt.llm_utils import create_chat_completion
7
+
8
+ CFG = Config()
9
+ MEMORY = get_memory(CFG)
10
+
11
+
12
+ def split_text(text: str, max_length: int = 8192) -> Generator[str, None, None]:
13
+ """Split text into chunks of a maximum length
14
+
15
+ Args:
16
+ text (str): The text to split
17
+ max_length (int, optional): The maximum length of each chunk. Defaults to 8192.
18
+
19
+ Yields:
20
+ str: The next chunk of text
21
+
22
+ Raises:
23
+ ValueError: If the text is longer than the maximum length
24
+ """
25
+ paragraphs = text.split("\n")
26
+ current_length = 0
27
+ current_chunk = []
28
+
29
+ for paragraph in paragraphs:
30
+ if current_length + len(paragraph) + 1 <= max_length:
31
+ current_chunk.append(paragraph)
32
+ current_length += len(paragraph) + 1
33
+ else:
34
+ yield "\n".join(current_chunk)
35
+ current_chunk = [paragraph]
36
+ current_length = len(paragraph) + 1
37
+
38
+ if current_chunk:
39
+ yield "\n".join(current_chunk)
40
+
41
+
42
+ def summarize_text(
43
+ url: str, text: str, question: str, driver: Optional[WebDriver] = None
44
+ ) -> str:
45
+ """Summarize text using the OpenAI API
46
+
47
+ Args:
48
+ url (str): The url of the text
49
+ text (str): The text to summarize
50
+ question (str): The question to ask the model
51
+ driver (WebDriver): The webdriver to use to scroll the page
52
+
53
+ Returns:
54
+ str: The summary of the text
55
+ """
56
+ if not text:
57
+ return "Error: No text to summarize"
58
+
59
+ text_length = len(text)
60
+ print(f"Text length: {text_length} characters")
61
+
62
+ summaries = []
63
+ chunks = list(split_text(text))
64
+ scroll_ratio = 1 / len(chunks)
65
+
66
+ for i, chunk in enumerate(chunks):
67
+ if driver:
68
+ scroll_to_percentage(driver, scroll_ratio * i)
69
+ print(f"Adding chunk {i + 1} / {len(chunks)} to memory")
70
+
71
+ memory_to_add = f"Source: {url}\n" f"Raw content part#{i + 1}: {chunk}"
72
+
73
+ MEMORY.add(memory_to_add)
74
+
75
+ print(f"Summarizing chunk {i + 1} / {len(chunks)}")
76
+ messages = [create_message(chunk, question)]
77
+
78
+ summary = create_chat_completion(
79
+ model=CFG.fast_llm_model,
80
+ messages=messages,
81
+ max_tokens=CFG.browse_summary_max_token,
82
+ )
83
+ summaries.append(summary)
84
+ print(f"Added chunk {i + 1} summary to memory")
85
+
86
+ memory_to_add = f"Source: {url}\n" f"Content summary part#{i + 1}: {summary}"
87
+
88
+ MEMORY.add(memory_to_add)
89
+
90
+ print(f"Summarized {len(chunks)} chunks.")
91
+
92
+ combined_summary = "\n".join(summaries)
93
+ messages = [create_message(combined_summary, question)]
94
+
95
+ return create_chat_completion(
96
+ model=CFG.fast_llm_model,
97
+ messages=messages,
98
+ max_tokens=CFG.browse_summary_max_token,
99
+ )
100
+
101
+
102
+ def scroll_to_percentage(driver: WebDriver, ratio: float) -> None:
103
+ """Scroll to a percentage of the page
104
+
105
+ Args:
106
+ driver (WebDriver): The webdriver to use
107
+ ratio (float): The percentage to scroll to
108
+
109
+ Raises:
110
+ ValueError: If the ratio is not between 0 and 1
111
+ """
112
+ if ratio < 0 or ratio > 1:
113
+ raise ValueError("Percentage should be between 0 and 1")
114
+ driver.execute_script(f"window.scrollTo(0, document.body.scrollHeight * {ratio});")
115
+
116
+
117
+ def create_message(chunk: str, question: str) -> Dict[str, str]:
118
+ """Create a message for the chat completion
119
+
120
+ Args:
121
+ chunk (str): The chunk of text to summarize
122
+ question (str): The question to answer
123
+
124
+ Returns:
125
+ Dict[str, str]: The message to send to the chat completion
126
+ """
127
+ return {
128
+ "role": "user",
129
+ "content": f'"""{chunk}""" Using the above text, answer the following'
130
+ f' question: "{question}" -- if the question cannot be answered using the text,'
131
+ " summarize the text.",
132
+ }
autogpt/setup.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Setup the AI and its goals"""
2
+ from colorama import Fore, Style
3
+ from autogpt import utils
4
+ from autogpt.config.ai_config import AIConfig
5
+ from autogpt.logs import logger
6
+
7
+
8
+ def prompt_user() -> AIConfig:
9
+ """Prompt the user for input
10
+
11
+ Returns:
12
+ AIConfig: The AIConfig object containing the user's input
13
+ """
14
+ ai_name = ""
15
+ # Construct the prompt
16
+ logger.typewriter_log(
17
+ "Welcome to Auto-GPT! ",
18
+ Fore.GREEN,
19
+ "Enter the name of your AI and its role below. Entering nothing will load"
20
+ " defaults.",
21
+ speak_text=True,
22
+ )
23
+
24
+ # Get AI Name from User
25
+ logger.typewriter_log(
26
+ "Name your AI: ", Fore.GREEN, "For example, 'Entrepreneur-GPT'"
27
+ )
28
+ ai_name = utils.clean_input("AI Name: ")
29
+ if ai_name == "":
30
+ ai_name = "Entrepreneur-GPT"
31
+
32
+ logger.typewriter_log(
33
+ f"{ai_name} here!", Fore.LIGHTBLUE_EX, "I am at your service.", speak_text=True
34
+ )
35
+
36
+ # Get AI Role from User
37
+ logger.typewriter_log(
38
+ "Describe your AI's role: ",
39
+ Fore.GREEN,
40
+ "For example, 'an AI designed to autonomously develop and run businesses with"
41
+ " the sole goal of increasing your net worth.'",
42
+ )
43
+ ai_role = utils.clean_input(f"{ai_name} is: ")
44
+ if ai_role == "":
45
+ ai_role = "an AI designed to autonomously develop and run businesses with the"
46
+ " sole goal of increasing your net worth."
47
+
48
+ # Enter up to 5 goals for the AI
49
+ logger.typewriter_log(
50
+ "Enter up to 5 goals for your AI: ",
51
+ Fore.GREEN,
52
+ "For example: \nIncrease net worth, Grow Twitter Account, Develop and manage"
53
+ " multiple businesses autonomously'",
54
+ )
55
+ print("Enter nothing to load defaults, enter nothing when finished.", flush=True)
56
+ ai_goals = []
57
+ for i in range(5):
58
+ ai_goal = utils.clean_input(f"{Fore.LIGHTBLUE_EX}Goal{Style.RESET_ALL} {i+1}: ")
59
+ if ai_goal == "":
60
+ break
61
+ ai_goals.append(ai_goal)
62
+ if not ai_goals:
63
+ ai_goals = [
64
+ "Increase net worth",
65
+ "Grow Twitter Account",
66
+ "Develop and manage multiple businesses autonomously",
67
+ ]
68
+
69
+ return AIConfig(ai_name, ai_role, ai_goals)
autogpt/speech/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """This module contains the speech recognition and speech synthesis functions."""
2
+ from autogpt.speech.say import say_text
3
+
4
+ __all__ = ["say_text"]
autogpt/speech/base.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Base class for all voice classes."""
2
+ import abc
3
+ from threading import Lock
4
+
5
+ from autogpt.config import AbstractSingleton
6
+
7
+
8
+ class VoiceBase(AbstractSingleton):
9
+ """
10
+ Base class for all voice classes.
11
+ """
12
+
13
+ def __init__(self):
14
+ """
15
+ Initialize the voice class.
16
+ """
17
+ self._url = None
18
+ self._headers = None
19
+ self._api_key = None
20
+ self._voices = []
21
+ self._mutex = Lock()
22
+ self._setup()
23
+
24
+ def say(self, text: str, voice_index: int = 0) -> bool:
25
+ """
26
+ Say the given text.
27
+
28
+ Args:
29
+ text (str): The text to say.
30
+ voice_index (int): The index of the voice to use.
31
+ """
32
+ with self._mutex:
33
+ return self._speech(text, voice_index)
34
+
35
+ @abc.abstractmethod
36
+ def _setup(self) -> None:
37
+ """
38
+ Setup the voices, API key, etc.
39
+ """
40
+ pass
41
+
42
+ @abc.abstractmethod
43
+ def _speech(self, text: str, voice_index: int = 0) -> bool:
44
+ """
45
+ Play the given text.
46
+
47
+ Args:
48
+ text (str): The text to play.
49
+ """
50
+ pass
autogpt/speech/brian.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Brian speech module for autogpt """
2
+ import os
3
+ import requests
4
+ from playsound import playsound
5
+
6
+ from autogpt.speech.base import VoiceBase
7
+
8
+
9
+ class BrianSpeech(VoiceBase):
10
+ """Brian speech module for autogpt"""
11
+
12
+ def _setup(self) -> None:
13
+ """Setup the voices, API key, etc."""
14
+ pass
15
+
16
+ def _speech(self, text: str) -> bool:
17
+ """Speak text using Brian with the streamelements API
18
+
19
+ Args:
20
+ text (str): The text to speak
21
+
22
+ Returns:
23
+ bool: True if the request was successful, False otherwise
24
+ """
25
+ tts_url = (
26
+ f"https://api.streamelements.com/kappa/v2/speech?voice=Brian&text={text}"
27
+ )
28
+ response = requests.get(tts_url)
29
+
30
+ if response.status_code == 200:
31
+ with open("speech.mp3", "wb") as f:
32
+ f.write(response.content)
33
+ playsound("speech.mp3")
34
+ os.remove("speech.mp3")
35
+ return True
36
+ else:
37
+ print("Request failed with status code:", response.status_code)
38
+ print("Response content:", response.content)
39
+ return False
autogpt/speech/eleven_labs.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ElevenLabs speech module"""
2
+ import os
3
+ from playsound import playsound
4
+
5
+ import requests
6
+
7
+ from autogpt.config import Config
8
+ from autogpt.speech.base import VoiceBase
9
+
10
+ PLACEHOLDERS = {"your-voice-id"}
11
+
12
+
13
+ class ElevenLabsSpeech(VoiceBase):
14
+ """ElevenLabs speech class"""
15
+
16
+ def _setup(self) -> None:
17
+ """Setup the voices, API key, etc.
18
+
19
+ Returns:
20
+ None: None
21
+ """
22
+
23
+ cfg = Config()
24
+ default_voices = ["ErXwobaYiN019PkySvjV", "EXAVITQu4vr4xnSDxMaL"]
25
+ self._headers = {
26
+ "Content-Type": "application/json",
27
+ "xi-api-key": cfg.elevenlabs_api_key,
28
+ }
29
+ self._voices = default_voices.copy()
30
+ self._use_custom_voice(cfg.elevenlabs_voice_1_id, 0)
31
+ self._use_custom_voice(cfg.elevenlabs_voice_2_id, 1)
32
+
33
+ def _use_custom_voice(self, voice, voice_index) -> None:
34
+ """Use a custom voice if provided and not a placeholder
35
+
36
+ Args:
37
+ voice (str): The voice ID
38
+ voice_index (int): The voice index
39
+
40
+ Returns:
41
+ None: None
42
+ """
43
+ # Placeholder values that should be treated as empty
44
+ if voice and voice not in PLACEHOLDERS:
45
+ self._voices[voice_index] = voice
46
+
47
+ def _speech(self, text: str, voice_index: int = 0) -> bool:
48
+ """Speak text using elevenlabs.io's API
49
+
50
+ Args:
51
+ text (str): The text to speak
52
+ voice_index (int, optional): The voice to use. Defaults to 0.
53
+
54
+ Returns:
55
+ bool: True if the request was successful, False otherwise
56
+ """
57
+ tts_url = (
58
+ f"https://api.elevenlabs.io/v1/text-to-speech/{self._voices[voice_index]}"
59
+ )
60
+ response = requests.post(tts_url, headers=self._headers, json={"text": text})
61
+
62
+ if response.status_code == 200:
63
+ with open("speech.mpeg", "wb") as f:
64
+ f.write(response.content)
65
+ playsound("speech.mpeg", True)
66
+ os.remove("speech.mpeg")
67
+ return True
68
+ else:
69
+ print("Request failed with status code:", response.status_code)
70
+ print("Response content:", response.content)
71
+ return False
autogpt/speech/gtts.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ GTTS Voice. """
2
+ import os
3
+ from playsound import playsound
4
+ import gtts
5
+
6
+ from autogpt.speech.base import VoiceBase
7
+
8
+
9
+ class GTTSVoice(VoiceBase):
10
+ """GTTS Voice."""
11
+
12
+ def _setup(self) -> None:
13
+ pass
14
+
15
+ def _speech(self, text: str, _: int = 0) -> bool:
16
+ """Play the given text."""
17
+ tts = gtts.gTTS(text)
18
+ tts.save("speech.mp3")
19
+ playsound("speech.mp3", True)
20
+ os.remove("speech.mp3")
21
+ return True
autogpt/speech/macos_tts.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ MacOS TTS Voice. """
2
+ import os
3
+
4
+ from autogpt.speech.base import VoiceBase
5
+
6
+
7
+ class MacOSTTS(VoiceBase):
8
+ """MacOS TTS Voice."""
9
+
10
+ def _setup(self) -> None:
11
+ pass
12
+
13
+ def _speech(self, text: str, voice_index: int = 0) -> bool:
14
+ """Play the given text."""
15
+ if voice_index == 0:
16
+ os.system(f'say "{text}"')
17
+ elif voice_index == 1:
18
+ os.system(f'say -v "Ava (Premium)" "{text}"')
19
+ else:
20
+ os.system(f'say -v Samantha "{text}"')
21
+ return True
autogpt/speech/say.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Text to speech module """
2
+ from autogpt.config import Config
3
+
4
+ import threading
5
+ from threading import Semaphore
6
+ from autogpt.speech.brian import BrianSpeech
7
+ from autogpt.speech.macos_tts import MacOSTTS
8
+ from autogpt.speech.gtts import GTTSVoice
9
+ from autogpt.speech.eleven_labs import ElevenLabsSpeech
10
+
11
+
12
+ CFG = Config()
13
+ DEFAULT_VOICE_ENGINE = GTTSVoice()
14
+ VOICE_ENGINE = None
15
+ if CFG.elevenlabs_api_key:
16
+ VOICE_ENGINE = ElevenLabsSpeech()
17
+ elif CFG.use_mac_os_tts == "True":
18
+ VOICE_ENGINE = MacOSTTS()
19
+ elif CFG.use_brian_tts == "True":
20
+ VOICE_ENGINE = BrianSpeech()
21
+ else:
22
+ VOICE_ENGINE = GTTSVoice()
23
+
24
+
25
+ QUEUE_SEMAPHORE = Semaphore(
26
+ 1
27
+ ) # The amount of sounds to queue before blocking the main thread
28
+
29
+
30
+ def say_text(text: str, voice_index: int = 0) -> None:
31
+ """Speak the given text using the given voice index"""
32
+
33
+ def speak() -> None:
34
+ success = VOICE_ENGINE.say(text, voice_index)
35
+ if not success:
36
+ DEFAULT_VOICE_ENGINE.say(text)
37
+
38
+ QUEUE_SEMAPHORE.release()
39
+
40
+ QUEUE_SEMAPHORE.acquire(True)
41
+ thread = threading.Thread(target=speak)
42
+ thread.start()
docs/imgs/openai-api-key-billing-paid-account.png ADDED
requirements-docker.txt ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ beautifulsoup4
2
+ colorama==0.4.6
3
+ openai==0.27.2
4
+ playsound==1.2.2
5
+ python-dotenv==1.0.0
6
+ pyyaml==6.0
7
+ readability-lxml==0.8.1
8
+ requests
9
+ tiktoken==0.3.3
10
+ gTTS==2.3.1
11
+ docker
12
+ duckduckgo-search
13
+ google-api-python-client #(https://developers.google.com/custom-search/v1/overview)
14
+ pinecone-client==2.2.1
15
+ redis
16
+ orjson
17
+ Pillow
18
+ selenium
19
+ webdriver-manager
20
+ coverage
21
+ flake8
22
+ numpy
23
+ pre-commit
24
+ black
25
+ isort
run.bat ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ python scripts/check_requirements.py requirements.txt
3
+ if errorlevel 1 (
4
+ echo Installing missing packages...
5
+ pip install -r requirements.txt
6
+ )
7
+ python -m autogpt %*
8
+ pause
run_continuous.bat ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ @echo off
2
+ set argument=--continuous
3
+ call run.bat %argument%