chatgpt-openai aliabid94 HF staff commited on
Commit
c73234c
0 Parent(s):

Duplicate from aliabid94/AutoGPT

Browse files

Co-authored-by: Ali Abid <aliabid94@users.noreply.huggingface.co>

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .devcontainer/Dockerfile +28 -0
  2. .devcontainer/devcontainer.json +40 -0
  3. .env.template +187 -0
  4. .envrc +4 -0
  5. .flake8 +12 -0
  6. .github/FUNDING.yml +3 -0
  7. .github/ISSUE_TEMPLATE/1.bug.yml +117 -0
  8. .github/ISSUE_TEMPLATE/2.feature.yml +29 -0
  9. .github/PULL_REQUEST_TEMPLATE.md +40 -0
  10. .github/workflows/auto_format.yml +23 -0
  11. .github/workflows/benchmark.yml +31 -0
  12. .github/workflows/ci.yml +72 -0
  13. .github/workflows/docker-image.yml +18 -0
  14. .github/workflows/dockerhub-imagepush.yml +24 -0
  15. .github/workflows/pr-label.yml +28 -0
  16. .gitignore +161 -0
  17. .pre-commit-config.yaml +32 -0
  18. .sourcery.yaml +71 -0
  19. BULLETIN.md +2 -0
  20. CODE_OF_CONDUCT.md +40 -0
  21. CONTRIBUTING.md +105 -0
  22. Dockerfile +38 -0
  23. LICENSE +21 -0
  24. README.md +13 -0
  25. autogpt/__init__.py +0 -0
  26. autogpt/__main__.py +5 -0
  27. autogpt/agent/__init__.py +4 -0
  28. autogpt/agent/agent.py +197 -0
  29. autogpt/agent/agent_manager.py +103 -0
  30. autogpt/app.py +330 -0
  31. autogpt/chat.py +175 -0
  32. autogpt/cli.py +145 -0
  33. autogpt/commands/__init__.py +0 -0
  34. autogpt/commands/analyze_code.py +25 -0
  35. autogpt/commands/audio_text.py +36 -0
  36. autogpt/commands/execute_code.py +158 -0
  37. autogpt/commands/file_operations.py +267 -0
  38. autogpt/commands/git_operations.py +26 -0
  39. autogpt/commands/google_search.py +87 -0
  40. autogpt/commands/image_gen.py +163 -0
  41. autogpt/commands/improve_code.py +29 -0
  42. autogpt/commands/times.py +10 -0
  43. autogpt/commands/twitter.py +26 -0
  44. autogpt/commands/web_playwright.py +80 -0
  45. autogpt/commands/web_requests.py +190 -0
  46. autogpt/commands/web_selenium.py +154 -0
  47. autogpt/commands/write_tests.py +31 -0
  48. autogpt/config/__init__.py +14 -0
  49. autogpt/config/ai_config.py +121 -0
  50. autogpt/config/config.py +251 -0
.devcontainer/Dockerfile ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # [Choice] Python version (use -bullseye variants on local arm64/Apple Silicon): 3, 3.10, 3-bullseye, 3.10-bullseye, 3-buster, 3.10-buster
2
+ ARG VARIANT=3-bullseye
3
+ FROM --platform=linux/amd64 python:3.10
4
+
5
+ RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
6
+ # Remove imagemagick due to https://security-tracker.debian.org/tracker/CVE-2019-10131
7
+ && apt-get purge -y imagemagick imagemagick-6-common
8
+
9
+ # Temporary: Upgrade python packages due to https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-40897
10
+ # They are installed by the base image (python) which does not have the patch.
11
+ RUN python3 -m pip install --upgrade setuptools
12
+
13
+ # Install Chrome for web browsing
14
+ RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
15
+ && curl -sSL https://dl.google.com/linux/direct/google-chrome-stable_current_$(dpkg --print-architecture).deb -o /tmp/chrome.deb \
16
+ && apt-get -y install /tmp/chrome.deb
17
+
18
+ # [Optional] If your pip requirements rarely change, uncomment this section to add them to the image.
19
+ # COPY requirements.txt /tmp/pip-tmp/
20
+ # RUN pip3 --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements.txt \
21
+ # && rm -rf /tmp/pip-tmp
22
+
23
+ # [Optional] Uncomment this section to install additional OS packages.
24
+ # RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
25
+ # && apt-get -y install --no-install-recommends <your-package-list-here>
26
+
27
+ # [Optional] Uncomment this line to install global node packages.
28
+ # RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g <your-package-here>" 2>&1
.devcontainer/devcontainer.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "build": {
3
+ "dockerfile": "./Dockerfile",
4
+ "context": "."
5
+ },
6
+ "features": {
7
+ "ghcr.io/devcontainers/features/common-utils:2": {
8
+ "installZsh": "true",
9
+ "username": "vscode",
10
+ "userUid": "1000",
11
+ "userGid": "1000",
12
+ "upgradePackages": "true"
13
+ },
14
+ "ghcr.io/devcontainers/features/desktop-lite:1": {},
15
+ "ghcr.io/devcontainers/features/python:1": "none",
16
+ "ghcr.io/devcontainers/features/node:1": "none",
17
+ "ghcr.io/devcontainers/features/git:1": {
18
+ "version": "latest",
19
+ "ppa": "false"
20
+ }
21
+ },
22
+ // Configure tool-specific properties.
23
+ "customizations": {
24
+ // Configure properties specific to VS Code.
25
+ "vscode": {
26
+ // Set *default* container specific settings.json values on container create.
27
+ "settings": {
28
+ "python.defaultInterpreterPath": "/usr/local/bin/python"
29
+ }
30
+ }
31
+ },
32
+ // Use 'forwardPorts' to make a list of ports inside the container available locally.
33
+ // "forwardPorts": [],
34
+
35
+ // Use 'postCreateCommand' to run commands after the container is created.
36
+ // "postCreateCommand": "pip3 install --user -r requirements.txt",
37
+
38
+ // Set `remoteUser` to `root` to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
39
+ "remoteUser": "vscode"
40
+ }
.env.template ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ################################################################################
2
+ ### AUTO-GPT - GENERAL SETTINGS
3
+ ################################################################################
4
+ # EXECUTE_LOCAL_COMMANDS - Allow local command execution (Example: False)
5
+ EXECUTE_LOCAL_COMMANDS=False
6
+ # RESTRICT_TO_WORKSPACE - Restrict file operations to workspace ./auto_gpt_workspace (Default: True)
7
+ RESTRICT_TO_WORKSPACE=True
8
+ # BROWSE_CHUNK_MAX_LENGTH - When browsing website, define the length of chunk stored in memory
9
+ BROWSE_CHUNK_MAX_LENGTH=8192
10
+ # USER_AGENT - Define the user-agent used by the requests library to browse website (string)
11
+ # USER_AGENT="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36"
12
+ # AI_SETTINGS_FILE - Specifies which AI Settings file to use (defaults to ai_settings.yaml)
13
+ AI_SETTINGS_FILE=ai_settings.yaml
14
+
15
+ ################################################################################
16
+ ### LLM PROVIDER
17
+ ################################################################################
18
+
19
+ ### OPENAI
20
+ # OPENAI_API_KEY - OpenAI API Key (Example: my-openai-api-key)
21
+ # TEMPERATURE - Sets temperature in OpenAI (Default: 0)
22
+ # USE_AZURE - Use Azure OpenAI or not (Default: False)
23
+ OPENAI_API_KEY=your-openai-api-key
24
+ TEMPERATURE=0
25
+ USE_AZURE=False
26
+
27
+ ### AZURE
28
+ # cleanup azure env as already moved to `azure.yaml.template`
29
+
30
+ ################################################################################
31
+ ### LLM MODELS
32
+ ################################################################################
33
+
34
+ # SMART_LLM_MODEL - Smart language model (Default: gpt-4)
35
+ # FAST_LLM_MODEL - Fast language model (Default: gpt-3.5-turbo)
36
+ SMART_LLM_MODEL=gpt-4
37
+ FAST_LLM_MODEL=gpt-3.5-turbo
38
+
39
+ ### LLM MODEL SETTINGS
40
+ # FAST_TOKEN_LIMIT - Fast token limit for OpenAI (Default: 4000)
41
+ # SMART_TOKEN_LIMIT - Smart token limit for OpenAI (Default: 8000)
42
+ # When using --gpt3only this needs to be set to 4000.
43
+ FAST_TOKEN_LIMIT=4000
44
+ SMART_TOKEN_LIMIT=8000
45
+
46
+ ################################################################################
47
+ ### MEMORY
48
+ ################################################################################
49
+
50
+ ### MEMORY_BACKEND - Memory backend type
51
+ # local - Default
52
+ # pinecone - Pinecone (if configured)
53
+ # redis - Redis (if configured)
54
+ # milvus - Milvus (if configured)
55
+ MEMORY_BACKEND=local
56
+
57
+ ### PINECONE
58
+ # PINECONE_API_KEY - Pinecone API Key (Example: my-pinecone-api-key)
59
+ # PINECONE_ENV - Pinecone environment (region) (Example: us-west-2)
60
+ PINECONE_API_KEY=your-pinecone-api-key
61
+ PINECONE_ENV=your-pinecone-region
62
+
63
+ ### REDIS
64
+ # REDIS_HOST - Redis host (Default: localhost, use "redis" for docker-compose)
65
+ # REDIS_PORT - Redis port (Default: 6379)
66
+ # REDIS_PASSWORD - Redis password (Default: "")
67
+ # WIPE_REDIS_ON_START - Wipes data / index on start (Default: False)
68
+ # MEMORY_INDEX - Name of index created in Redis database (Default: auto-gpt)
69
+ REDIS_HOST=localhost
70
+ REDIS_PORT=6379
71
+ REDIS_PASSWORD=
72
+ WIPE_REDIS_ON_START=False
73
+ MEMORY_INDEX=auto-gpt
74
+
75
+ ### WEAVIATE
76
+ # MEMORY_BACKEND - Use 'weaviate' to use Weaviate vector storage
77
+ # WEAVIATE_HOST - Weaviate host IP
78
+ # WEAVIATE_PORT - Weaviate host port
79
+ # WEAVIATE_PROTOCOL - Weaviate host protocol (e.g. 'http')
80
+ # USE_WEAVIATE_EMBEDDED - Whether to use Embedded Weaviate
81
+ # WEAVIATE_EMBEDDED_PATH - File system path were to persist data when running Embedded Weaviate
82
+ # WEAVIATE_USERNAME - Weaviate username
83
+ # WEAVIATE_PASSWORD - Weaviate password
84
+ # WEAVIATE_API_KEY - Weaviate API key if using API-key-based authentication
85
+ # MEMORY_INDEX - Name of index to create in Weaviate
86
+ WEAVIATE_HOST="127.0.0.1"
87
+ WEAVIATE_PORT=8080
88
+ WEAVIATE_PROTOCOL="http"
89
+ USE_WEAVIATE_EMBEDDED=False
90
+ WEAVIATE_EMBEDDED_PATH="/home/me/.local/share/weaviate"
91
+ WEAVIATE_USERNAME=
92
+ WEAVIATE_PASSWORD=
93
+ WEAVIATE_API_KEY=
94
+ MEMORY_INDEX=AutoGpt
95
+
96
+ ### MILVUS
97
+ # MILVUS_ADDR - Milvus remote address (e.g. localhost:19530)
98
+ # MILVUS_COLLECTION - Milvus collection,
99
+ # change it if you want to start a new memory and retain the old memory.
100
+ MILVUS_ADDR=your-milvus-cluster-host-port
101
+ MILVUS_COLLECTION=autogpt
102
+
103
+ ################################################################################
104
+ ### IMAGE GENERATION PROVIDER
105
+ ################################################################################
106
+
107
+ ### OPEN AI
108
+ # IMAGE_PROVIDER - Image provider (Example: dalle)
109
+ IMAGE_PROVIDER=dalle
110
+ # IMAGE_SIZE - Image size (Example: 256)
111
+ # DALLE: 256, 512, 1024
112
+ IMAGE_SIZE=256
113
+
114
+ ### HUGGINGFACE
115
+ # HUGGINGFACE_IMAGE_MODEL - Text-to-image model from Huggingface (Default: CompVis/stable-diffusion-v1-4)
116
+ HUGGINGFACE_IMAGE_MODEL=CompVis/stable-diffusion-v1-4
117
+ # HUGGINGFACE_API_TOKEN - HuggingFace API token (Example: my-huggingface-api-token)
118
+ HUGGINGFACE_API_TOKEN=your-huggingface-api-token
119
+
120
+ ### STABLE DIFFUSION WEBUI
121
+ # SD_WEBUI_URL - Stable diffusion webui API URL (Example: http://127.0.0.1:7860)
122
+ SD_WEBUI_URL=http://127.0.0.1:7860
123
+ # SD_WEBUI_AUTH - Stable diffusion webui username:password pair (Example: username:password)
124
+ SD_WEBUI_AUTH=
125
+
126
+ ################################################################################
127
+ ### AUDIO TO TEXT PROVIDER
128
+ ################################################################################
129
+
130
+ ### HUGGINGFACE
131
+ HUGGINGFACE_AUDIO_TO_TEXT_MODEL=facebook/wav2vec2-base-960h
132
+
133
+ ################################################################################
134
+ ### GIT Provider for repository actions
135
+ ################################################################################
136
+
137
+ ### GITHUB
138
+ # GITHUB_API_KEY - Github API key / PAT (Example: github_pat_123)
139
+ # GITHUB_USERNAME - Github username
140
+ GITHUB_API_KEY=github_pat_123
141
+ GITHUB_USERNAME=your-github-username
142
+
143
+ ################################################################################
144
+ ### WEB BROWSING
145
+ ################################################################################
146
+
147
+ ### BROWSER
148
+ # USE_WEB_BROWSER - Sets the web-browser drivers to use with selenium (defaults to chrome).
149
+ # HEADLESS_BROWSER - Whether to run the browser in headless mode (defaults to True)
150
+ # Note: set this to either 'chrome', 'firefox', or 'safari' depending on your current browser
151
+ # USE_WEB_BROWSER=chrome
152
+ # HEADLESS_BROWSER=True
153
+
154
+ ### GOOGLE
155
+ # GOOGLE_API_KEY - Google API key (Example: my-google-api-key)
156
+ # CUSTOM_SEARCH_ENGINE_ID - Custom search engine ID (Example: my-custom-search-engine-id)
157
+ GOOGLE_API_KEY=your-google-api-key
158
+ CUSTOM_SEARCH_ENGINE_ID=your-custom-search-engine-id
159
+
160
+ ################################################################################
161
+ ### TTS PROVIDER
162
+ ################################################################################
163
+
164
+ ### MAC OS
165
+ # USE_MAC_OS_TTS - Use Mac OS TTS or not (Default: False)
166
+ USE_MAC_OS_TTS=False
167
+
168
+ ### STREAMELEMENTS
169
+ # USE_BRIAN_TTS - Use Brian TTS or not (Default: False)
170
+ USE_BRIAN_TTS=False
171
+
172
+ ### ELEVENLABS
173
+ # ELEVENLABS_API_KEY - Eleven Labs API key (Example: my-elevenlabs-api-key)
174
+ # ELEVENLABS_VOICE_1_ID - Eleven Labs voice 1 ID (Example: my-voice-id-1)
175
+ # ELEVENLABS_VOICE_2_ID - Eleven Labs voice 2 ID (Example: my-voice-id-2)
176
+ ELEVENLABS_API_KEY=your-elevenlabs-api-key
177
+ ELEVENLABS_VOICE_1_ID=your-voice-id-1
178
+ ELEVENLABS_VOICE_2_ID=your-voice-id-2
179
+
180
+ ################################################################################
181
+ ### TWITTER API
182
+ ################################################################################
183
+
184
+ TW_CONSUMER_KEY=
185
+ TW_CONSUMER_SECRET=
186
+ TW_ACCESS_TOKEN=
187
+ TW_ACCESS_TOKEN_SECRET=
.envrc ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Upon entering directory, direnv requests user permission once to automatically load project dependencies onwards.
2
+ # Eliminating the need of running "nix develop github:superherointj/nix-auto-gpt" for Nix users to develop/use Auto-GPT.
3
+
4
+ [[ -z $IN_NIX_SHELL ]] && use flake github:superherointj/nix-auto-gpt
.flake8 ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [flake8]
2
+ max-line-length = 88
3
+ select = "E303, W293, W291, W292, E305, E231, E302"
4
+ exclude =
5
+ .tox,
6
+ __pycache__,
7
+ *.pyc,
8
+ .env
9
+ venv*/*,
10
+ .venv/*,
11
+ reports/*,
12
+ dist/*,
.github/FUNDING.yml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # These are supported funding model platforms
2
+
3
+ github: Torantulino
.github/ISSUE_TEMPLATE/1.bug.yml ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Bug report 🐛
2
+ description: Create a bug report for Auto-GPT.
3
+ labels: ['status: needs triage']
4
+ body:
5
+ - type: markdown
6
+ attributes:
7
+ value: |
8
+ ### ⚠️ Before you continue
9
+ * Check out our [backlog], [roadmap] and join our [discord] to discuss what's going on
10
+ * If you need help, you can ask in the [discussions] section or in [#tech-support]
11
+ * **Throughly search the [existing issues] before creating a new one**
12
+
13
+ [backlog]: https://github.com/orgs/Significant-Gravitas/projects/1
14
+ [roadmap]: https://github.com/orgs/Significant-Gravitas/projects/2
15
+ [discord]: https://discord.gg/autogpt
16
+ [discussions]: https://github.com/Significant-Gravitas/Auto-GPT/discussions
17
+ [#tech-support]: https://discord.com/channels/1092243196446249134/1092275629602394184
18
+ [existing issues]: https://github.com/Significant-Gravitas/Auto-GPT/issues?q=is%3Aissue
19
+ - type: checkboxes
20
+ attributes:
21
+ label: ⚠️ Search for existing issues first ⚠️
22
+ description: >
23
+ Please [search the history](https://github.com/Torantulino/Auto-GPT/issues)
24
+ to see if an issue already exists for the same problem.
25
+ options:
26
+ - label: I have searched the existing issues, and there is no existing issue for my problem
27
+ required: true
28
+ - type: markdown
29
+ attributes:
30
+ value: |
31
+ Please provide a searchable summary of the issue in the title above ⬆️.
32
+
33
+ ⚠️ SUPER-busy repo, please help the volunteer maintainers.
34
+ The less time we spend here, the more time we spend building AutoGPT.
35
+
36
+ Please help us help you:
37
+ - Does it work on `stable` branch (https://github.com/Torantulino/Auto-GPT/tree/stable)?
38
+ - Does it work on current `master` (https://github.com/Torantulino/Auto-GPT/tree/master)?
39
+ - Search for existing issues, "add comment" is tidier than "new issue"
40
+ - Ask on our Discord (https://discord.gg/autogpt)
41
+ - Provide relevant info:
42
+ - Provide commit-hash (`git rev-parse HEAD` gets it)
43
+ - If it's a pip/packages issue, provide pip version, python version
44
+ - If it's a crash, provide traceback.
45
+ - type: dropdown
46
+ attributes:
47
+ label: Which Operating System are you using?
48
+ description: >
49
+ Please select the operating system you were using to run Auto-GPT when this problem occurred.
50
+ options:
51
+ - Windows
52
+ - Linux
53
+ - MacOS
54
+ - Docker
55
+ - Devcontainer / Codespace
56
+ - Windows Subsystem for Linux (WSL)
57
+ - Other (Please specify in your problem)
58
+ validations:
59
+ required: true
60
+ - type: dropdown
61
+ attributes:
62
+ label: GPT-3 or GPT-4?
63
+ description: >
64
+ If you are using Auto-GPT with `--gpt3only`, your problems may be caused by
65
+ the [limitations](https://github.com/Significant-Gravitas/Auto-GPT/issues?q=is%3Aissue+label%3A%22AI+model+limitation%22) of GPT-3.5.
66
+ options:
67
+ - GPT-3.5
68
+ - GPT-4
69
+ validations:
70
+ required: true
71
+ - type: textarea
72
+ attributes:
73
+ label: Steps to reproduce 🕹
74
+ description: |
75
+ **⚠️ Issues that we can't reproduce will be closed.**
76
+ - type: textarea
77
+ attributes:
78
+ label: Current behavior 😯
79
+ description: Describe what happens instead of the expected behavior.
80
+ - type: textarea
81
+ attributes:
82
+ label: Expected behavior 🤔
83
+ description: Describe what should happen.
84
+ - type: textarea
85
+ attributes:
86
+ label: Your prompt 📝
87
+ description: >
88
+ If applicable please provide the prompt you are using. Your prompt is stored in your `ai_settings.yaml` file.
89
+ value: |
90
+ ```yaml
91
+ # Paste your prompt here
92
+ ```
93
+ - type: textarea
94
+ attributes:
95
+ label: Your Logs 📒
96
+ description: |
97
+ Please include the log showing your error and the command that caused it, if applicable.
98
+ You can copy it from your terminal or from `logs/activity.log`.
99
+ This will help us understand your issue better!
100
+
101
+ <details>
102
+ <summary><i>Example</i></summary>
103
+ ```log
104
+ INFO NEXT ACTION: COMMAND = execute_shell ARGUMENTS = {'command_line': 'some_command'}
105
+ INFO -=-=-=-=-=-=-= COMMAND AUTHORISED BY USER -=-=-=-=-=-=-=
106
+ Traceback (most recent call last):
107
+ File "/home/anaconda3/lib/python3.9/site-packages/openai/api_requestor.py", line 619, in _interpret_response
108
+ self._interpret_response_line(
109
+ File "/home/anaconda3/lib/python3.9/site-packages/openai/api_requestor.py", line 682, in _interpret_response_line
110
+ raise self.handle_error_response(
111
+ openai.error.InvalidRequestError: This model's maximum context length is 8191 tokens, however you requested 10982 tokens (10982 in your prompt; 0 for the completion). Please reduce your prompt; or completion length.
112
+ ```
113
+ </details>
114
+ value: |
115
+ ```log
116
+ <insert your logs here>
117
+ ```
.github/ISSUE_TEMPLATE/2.feature.yml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Feature request 🚀
2
+ description: Suggest a new idea for Auto-GPT.
3
+ labels: ['status: needs triage']
4
+ body:
5
+ - type: markdown
6
+ attributes:
7
+ value: |
8
+ Please provide a searchable summary of the issue in the title above ⬆️.
9
+
10
+ Thanks for contributing by creating an issue! ❤️
11
+ - type: checkboxes
12
+ attributes:
13
+ label: Duplicates
14
+ description: Please [search the history](https://github.com/Torantulino/Auto-GPT/issues) to see if an issue already exists for the same problem.
15
+ options:
16
+ - label: I have searched the existing issues
17
+ required: true
18
+ - type: textarea
19
+ attributes:
20
+ label: Summary 💡
21
+ description: Describe how it should work.
22
+ - type: textarea
23
+ attributes:
24
+ label: Examples 🌈
25
+ description: Provide a link to other implementations, or screenshots of the expected behavior.
26
+ - type: textarea
27
+ attributes:
28
+ label: Motivation 🔦
29
+ description: What are you trying to accomplish? How has the lack of this feature affected you? Providing context helps us come up with a solution that is more useful in the real world.
.github/PULL_REQUEST_TEMPLATE.md ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- ⚠️ At the moment any non-essential commands are not being merged.
2
+ If you want to add non-essential commands to Auto-GPT, please create a plugin instead.
3
+ We are expecting to ship plugin support within the week (PR #757).
4
+ Resources:
5
+ * https://github.com/Significant-Gravitas/Auto-GPT-Plugin-Template
6
+ -->
7
+
8
+ <!-- 📢 Announcement
9
+ We've recently noticed an increase in pull requests focusing on combining multiple changes. While the intentions behind these PRs are appreciated, it's essential to maintain a clean and manageable git history. To ensure the quality of our repository, we kindly ask you to adhere to the following guidelines when submitting PRs:
10
+
11
+ Focus on a single, specific change.
12
+ Do not include any unrelated or "extra" modifications.
13
+ Provide clear documentation and explanations of the changes made.
14
+ Ensure diffs are limited to the intended lines — no applying preferred formatting styles or line endings (unless that's what the PR is about).
15
+ For guidance on committing only the specific lines you have changed, refer to this helpful video: https://youtu.be/8-hSNHHbiZg
16
+
17
+ By following these guidelines, your PRs are more likely to be merged quickly after testing, as long as they align with the project's overall direction. -->
18
+
19
+ ### Background
20
+ <!-- Provide a concise overview of the rationale behind this change. Include relevant context, prior discussions, or links to related issues. Ensure that the change aligns with the project's overall direction. -->
21
+
22
+ ### Changes
23
+ <!-- Describe the specific, focused change made in this pull request. Detail the modifications clearly and avoid any unrelated or "extra" changes. -->
24
+
25
+ ### Documentation
26
+ <!-- Explain how your changes are documented, such as in-code comments or external documentation. Ensure that the documentation is clear, concise, and easy to understand. -->
27
+
28
+ ### Test Plan
29
+ <!-- Describe how you tested this functionality. Include steps to reproduce, relevant test cases, and any other pertinent information. -->
30
+
31
+ ### PR Quality Checklist
32
+ - [ ] My pull request is atomic and focuses on a single change.
33
+ - [ ] I have thoroughly tested my changes with multiple different prompts.
34
+ - [ ] I have considered potential risks and mitigations for my changes.
35
+ - [ ] I have documented my changes clearly and comprehensively.
36
+ - [ ] I have not snuck in any "extra" small tweaks changes <!-- Submit these as separate Pull Requests, they are the easiest to merge! -->
37
+
38
+ <!-- If you haven't added tests, please explain why. If you have, check the appropriate box. If you've ensured your PR is atomic and well-documented, check the corresponding boxes. -->
39
+
40
+ <!-- By submitting this, I agree that my pull request should be closed if I do not fill this out or follow the guidelines. -->
.github/workflows/auto_format.yml ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: auto-format
2
+ on: pull_request
3
+ jobs:
4
+ format:
5
+ runs-on: ubuntu-latest
6
+ steps:
7
+ - name: Checkout PR branch
8
+ uses: actions/checkout@v2
9
+ with:
10
+ ref: ${{ github.event.pull_request.head.sha }}
11
+ - name: autopep8
12
+ uses: peter-evans/autopep8@v1
13
+ with:
14
+ args: --exit-code --recursive --in-place --aggressive --aggressive .
15
+ - name: Check for modified files
16
+ id: git-check
17
+ run: echo "modified=$(if git diff-index --quiet HEAD --; then echo "false"; else echo "true"; fi)" >> $GITHUB_ENV
18
+ - name: Push changes
19
+ if: steps.git-check.outputs.modified == 'true'
20
+ run: |
21
+ git config --global user.name 'Torantulino'
22
+ git config --global user.email 'toran.richards@gmail.com'
23
+ git remote set
.github/workflows/benchmark.yml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: benchmark
2
+
3
+ on:
4
+ workflow_dispatch:
5
+
6
+ jobs:
7
+ build:
8
+ runs-on: ubuntu-latest
9
+ environment: benchmark
10
+ strategy:
11
+ matrix:
12
+ python-version: ['3.10', '3.11']
13
+
14
+ steps:
15
+ - name: Check out repository
16
+ uses: actions/checkout@v3
17
+
18
+ - name: Set up Python ${{ matrix.python-version }}
19
+ uses: actions/setup-python@v2
20
+ with:
21
+ python-version: ${{ matrix.python-version }}
22
+
23
+ - name: Install dependencies
24
+ run: |
25
+ python -m pip install --upgrade pip
26
+ pip install -r requirements.txt
27
+ - name: benchmark
28
+ run: |
29
+ python benchmark/benchmark_entrepeneur_gpt_with_undecisive_user.py
30
+ env:
31
+ OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
.github/workflows/ci.yml ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Python CI
2
+
3
+ on:
4
+ push:
5
+ branches: [master]
6
+ pull_request:
7
+ branches: [master]
8
+
9
+ concurrency:
10
+ group: ${{ format('ci-{0}', format('pr-{0}', github.event.pull_request.number) || github.sha) }}
11
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
12
+
13
+ jobs:
14
+ lint:
15
+ runs-on: ubuntu-latest
16
+ env:
17
+ min-python-version: '3.10'
18
+
19
+ steps:
20
+ - name: Check out repository
21
+ uses: actions/checkout@v3
22
+
23
+ - name: Set up Python ${{ env.min-python-version }}
24
+ uses: actions/setup-python@v2
25
+ with:
26
+ python-version: ${{ env.min-python-version }}
27
+
28
+ - name: Install dependencies
29
+ run: |
30
+ python -m pip install --upgrade pip
31
+ pip install -r requirements.txt
32
+
33
+ - name: Lint with flake8
34
+ run: flake8
35
+
36
+ - name: Check black formatting
37
+ run: black . --check
38
+ if: success() || failure()
39
+
40
+ - name: Check isort formatting
41
+ run: isort . --check
42
+ if: success() || failure()
43
+
44
+ test:
45
+ runs-on: ubuntu-latest
46
+ strategy:
47
+ matrix:
48
+ python-version: ['3.10', '3.11']
49
+
50
+ steps:
51
+ - name: Check out repository
52
+ uses: actions/checkout@v3
53
+
54
+ - name: Set up Python ${{ matrix.python-version }}
55
+ uses: actions/setup-python@v2
56
+ with:
57
+ python-version: ${{ matrix.python-version }}
58
+
59
+ - name: Install dependencies
60
+ run: |
61
+ python -m pip install --upgrade pip
62
+ pip install -r requirements.txt
63
+
64
+ - name: Run unittest tests with coverage
65
+ run: |
66
+ pytest --cov=autogpt --without-integration --without-slow-integration
67
+
68
+ - name: Generate coverage report
69
+ run: |
70
+ coverage report
71
+ coverage xml
72
+ if: success() || failure()
.github/workflows/docker-image.yml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Docker Image CI
2
+
3
+ on:
4
+ push:
5
+ branches: [ "master" ]
6
+ pull_request:
7
+ branches: [ "master" ]
8
+
9
+ jobs:
10
+
11
+ build:
12
+
13
+ runs-on: ubuntu-latest
14
+
15
+ steps:
16
+ - uses: actions/checkout@v3
17
+ - name: Build the Docker image
18
+ run: docker build . --file Dockerfile --tag autogpt:$(date +%s)
.github/workflows/dockerhub-imagepush.yml ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Push Docker Image on Release
2
+
3
+ on:
4
+ push:
5
+ branches: [ "stable" ]
6
+
7
+ jobs:
8
+
9
+ build:
10
+
11
+ runs-on: ubuntu-latest
12
+
13
+ steps:
14
+ - uses: actions/checkout@v3
15
+ - name: Log in to Docker hub
16
+ env:
17
+ DOCKER_USER: ${{secrets.DOCKER_USER}}
18
+ DOCKER_PASSWORD: ${{secrets.DOCKER_PASSWORD}}
19
+ run: |
20
+ docker login -u $DOCKER_USER -p $DOCKER_PASSWORD
21
+ - name: Build the Docker image
22
+ run: docker build . --file Dockerfile --tag ${{secrets.DOCKER_USER}}/auto-gpt:$(git describe --tags `git rev-list --tags --max-count=1`)
23
+ - name: Docker Push
24
+ run: docker push ${{secrets.DOCKER_USER}}/auto-gpt
.github/workflows/pr-label.yml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: "Pull Request auto-label"
2
+ on:
3
+ # So that PRs touching the same files as the push are updated
4
+ push:
5
+ # So that the `dirtyLabel` is removed if conflicts are resolve
6
+ # We recommend `pull_request_target` so that github secrets are available.
7
+ # In `pull_request` we wouldn't be able to change labels of fork PRs
8
+ pull_request_target:
9
+ types: [opened, synchronize]
10
+ concurrency:
11
+ group: ${{ format('pr-label-{0}', github.event.pull_request.number || github.sha) }}
12
+ cancel-in-progress: true
13
+
14
+ jobs:
15
+ conflicts:
16
+ runs-on: ubuntu-latest
17
+ permissions:
18
+ contents: read
19
+ pull-requests: write
20
+ steps:
21
+ - name: Update PRs with conflict labels
22
+ uses: eps1lon/actions-label-merge-conflict@releases/2.x
23
+ with:
24
+ dirtyLabel: "conflicts"
25
+ #removeOnDirtyLabel: "PR: ready to ship"
26
+ repoToken: "${{ secrets.GITHUB_TOKEN }}"
27
+ commentOnDirty: "This pull request has conflicts with the base branch, please resolve those so we can evaluate the pull request."
28
+ commentOnClean: "Conflicts have been resolved! 🎉 A maintainer will review the pull request shortly."
.gitignore ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Original ignores
2
+ autogpt/keys.py
3
+ autogpt/*json
4
+ autogpt/node_modules/
5
+ autogpt/__pycache__/keys.cpython-310.pyc
6
+ autogpt/auto_gpt_workspace
7
+ package-lock.json
8
+ *.pyc
9
+ auto_gpt_workspace/*
10
+ *.mpeg
11
+ .env
12
+ azure.yaml
13
+ ai_settings.yaml
14
+ last_run_ai_settings.yaml
15
+ .vscode
16
+ .idea/*
17
+ auto-gpt.json
18
+ log.txt
19
+ log-ingestion.txt
20
+ logs
21
+ *.log
22
+ *.mp3
23
+
24
+ # Byte-compiled / optimized / DLL files
25
+ __pycache__/
26
+ *.py[cod]
27
+ *$py.class
28
+
29
+ # C extensions
30
+ *.so
31
+
32
+ # Distribution / packaging
33
+ .Python
34
+ build/
35
+ develop-eggs/
36
+ dist/
37
+ plugins/
38
+ downloads/
39
+ eggs/
40
+ .eggs/
41
+ lib/
42
+ lib64/
43
+ parts/
44
+ sdist/
45
+ var/
46
+ wheels/
47
+ pip-wheel-metadata/
48
+ share/python-wheels/
49
+ *.egg-info/
50
+ .installed.cfg
51
+ *.egg
52
+ MANIFEST
53
+
54
+ # PyInstaller
55
+ # Usually these files are written by a python script from a template
56
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
57
+ *.manifest
58
+ *.spec
59
+
60
+ # Installer logs
61
+ pip-log.txt
62
+ pip-delete-this-directory.txt
63
+
64
+ # Unit test / coverage reports
65
+ htmlcov/
66
+ .tox/
67
+ .nox/
68
+ .coverage
69
+ .coverage.*
70
+ .cache
71
+ nosetests.xml
72
+ coverage.xml
73
+ *.cover
74
+ *.py,cover
75
+ .hypothesis/
76
+ .pytest_cache/
77
+
78
+ # Translations
79
+ *.mo
80
+ *.pot
81
+
82
+ # Django stuff:
83
+ *.log
84
+ local_settings.py
85
+ db.sqlite3
86
+ db.sqlite3-journal
87
+
88
+ # Flask stuff:
89
+ instance/
90
+ .webassets-cache
91
+
92
+ # Scrapy stuff:
93
+ .scrapy
94
+
95
+ # Sphinx documentation
96
+ docs/_build/
97
+
98
+ # PyBuilder
99
+ target/
100
+
101
+ # Jupyter Notebook
102
+ .ipynb_checkpoints
103
+
104
+ # IPython
105
+ profile_default/
106
+ ipython_config.py
107
+
108
+ # pyenv
109
+ .python-version
110
+
111
+ # pipenv
112
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
113
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
114
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
115
+ # install all needed dependencies.
116
+ #Pipfile.lock
117
+
118
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
119
+ __pypackages__/
120
+
121
+ # Celery stuff
122
+ celerybeat-schedule
123
+ celerybeat.pid
124
+
125
+ # SageMath parsed files
126
+ *.sage.py
127
+
128
+ # Environments
129
+ .direnv/
130
+ .env
131
+ .venv
132
+ env/
133
+ venv*/
134
+ ENV/
135
+ env.bak/
136
+
137
+ # Spyder project settings
138
+ .spyderproject
139
+ .spyproject
140
+
141
+ # Rope project settings
142
+ .ropeproject
143
+
144
+ # mkdocs documentation
145
+ /site
146
+
147
+ # mypy
148
+ .mypy_cache/
149
+ .dmypy.json
150
+ dmypy.json
151
+
152
+ # Pyre type checker
153
+ .pyre/
154
+ llama-*
155
+ vicuna-*
156
+
157
+ # mac
158
+ .DS_Store
159
+
160
+ # news
161
+ CURRENT_BULLETIN.md
.pre-commit-config.yaml ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ - repo: https://github.com/pre-commit/pre-commit-hooks
3
+ rev: v0.9.2
4
+ hooks:
5
+ - id: check-added-large-files
6
+ args: ['--maxkb=500']
7
+ - id: check-byte-order-marker
8
+ - id: check-case-conflict
9
+ - id: check-merge-conflict
10
+ - id: check-symlinks
11
+ - id: debug-statements
12
+
13
+ - repo: https://github.com/pycqa/isort
14
+ rev: 5.12.0
15
+ hooks:
16
+ - id: isort
17
+ language_version: python3.10
18
+
19
+ - repo: https://github.com/psf/black
20
+ rev: 23.3.0
21
+ hooks:
22
+ - id: black
23
+ language_version: python3.10
24
+
25
+ - repo: local
26
+ hooks:
27
+ - id: pytest-check
28
+ name: pytest-check
29
+ entry: pytest --cov=autogpt --without-integration --without-slow-integration
30
+ language: system
31
+ pass_filenames: false
32
+ always_run: true
.sourcery.yaml ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🪄 This is your project's Sourcery configuration file.
2
+
3
+ # You can use it to get Sourcery working in the way you want, such as
4
+ # ignoring specific refactorings, skipping directories in your project,
5
+ # or writing custom rules.
6
+
7
+ # 📚 For a complete reference to this file, see the documentation at
8
+ # https://docs.sourcery.ai/Configuration/Project-Settings/
9
+
10
+ # This file was auto-generated by Sourcery on 2023-02-25 at 21:07.
11
+
12
+ version: '1' # The schema version of this config file
13
+
14
+ ignore: # A list of paths or files which Sourcery will ignore.
15
+ - .git
16
+ - venv
17
+ - .venv
18
+ - build
19
+ - dist
20
+ - env
21
+ - .env
22
+ - .tox
23
+
24
+ rule_settings:
25
+ enable:
26
+ - default
27
+ - gpsg
28
+ disable: [] # A list of rule IDs Sourcery will never suggest.
29
+ rule_types:
30
+ - refactoring
31
+ - suggestion
32
+ - comment
33
+ python_version: '3.10' # A string specifying the lowest Python version your project supports. Sourcery will not suggest refactorings requiring a higher Python version.
34
+
35
+ # rules: # A list of custom rules Sourcery will include in its analysis.
36
+ # - id: no-print-statements
37
+ # description: Do not use print statements in the test directory.
38
+ # pattern: print(...)
39
+ # language: python
40
+ # replacement:
41
+ # condition:
42
+ # explanation:
43
+ # paths:
44
+ # include:
45
+ # - test
46
+ # exclude:
47
+ # - conftest.py
48
+ # tests: []
49
+ # tags: []
50
+
51
+ # rule_tags: {} # Additional rule tags.
52
+
53
+ # metrics:
54
+ # quality_threshold: 25.0
55
+
56
+ # github:
57
+ # labels: []
58
+ # ignore_labels:
59
+ # - sourcery-ignore
60
+ # request_review: author
61
+ # sourcery_branch: sourcery/{base_branch}
62
+
63
+ # clone_detection:
64
+ # min_lines: 3
65
+ # min_duplicates: 2
66
+ # identical_clones_only: false
67
+
68
+ # proxy:
69
+ # url:
70
+ # ssl_certs_file:
71
+ # no_ssl_verify: false
BULLETIN.md ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ Welcome to Auto-GPT! We'll keep you informed of the latest news and features by printing messages here.
2
+ If you don't wish to see this message, you can run Auto-GPT with the --skip-news flag
CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Code of Conduct for auto-gpt
2
+
3
+ ## 1. Purpose
4
+
5
+ The purpose of this Code of Conduct is to provide guidelines for contributors to the auto-gpt project on GitHub. We aim to create a positive and inclusive environment where all participants can contribute and collaborate effectively. By participating in this project, you agree to abide by this Code of Conduct.
6
+
7
+ ## 2. Scope
8
+
9
+ This Code of Conduct applies to all contributors, maintainers, and users of the auto-gpt project. It extends to all project spaces, including but not limited to issues, pull requests, code reviews, comments, and other forms of communication within the project.
10
+
11
+ ## 3. Our Standards
12
+
13
+ We encourage the following behavior:
14
+
15
+ * Being respectful and considerate to others
16
+ * Actively seeking diverse perspectives
17
+ * Providing constructive feedback and assistance
18
+ * Demonstrating empathy and understanding
19
+
20
+ We discourage the following behavior:
21
+
22
+ * Harassment or discrimination of any kind
23
+ * Disrespectful, offensive, or inappropriate language or content
24
+ * Personal attacks or insults
25
+ * Unwarranted criticism or negativity
26
+
27
+ ## 4. Reporting and Enforcement
28
+
29
+ If you witness or experience any violations of this Code of Conduct, please report them to the project maintainers by email or other appropriate means. The maintainers will investigate and take appropriate action, which may include warnings, temporary or permanent bans, or other measures as necessary.
30
+
31
+ Maintainers are responsible for ensuring compliance with this Code of Conduct and may take action to address any violations.
32
+
33
+ ## 5. Acknowledgements
34
+
35
+ This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/version/2/0/code_of_conduct.html).
36
+
37
+ ## 6. Contact
38
+
39
+ If you have any questions or concerns, please contact the project maintainers.
40
+
CONTRIBUTING.md ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to ProjectName
2
+
3
+ First of all, thank you for considering contributing to our project! We appreciate your time and effort, and we value any contribution, whether it's reporting a bug, suggesting a new feature, or submitting a pull request.
4
+
5
+ This document provides guidelines and best practices to help you contribute effectively.
6
+
7
+ ## Table of Contents
8
+
9
+ - [Code of Conduct](#code-of-conduct)
10
+ - [Getting Started](#getting-started)
11
+ - [How to Contribute](#how-to-contribute)
12
+ - [Reporting Bugs](#reporting-bugs)
13
+ - [Suggesting Enhancements](#suggesting-enhancements)
14
+ - [Submitting Pull Requests](#submitting-pull-requests)
15
+ - [Style Guidelines](#style-guidelines)
16
+ - [Code Formatting](#code-formatting)
17
+ - [Pre-Commit Hooks](#pre-commit-hooks)
18
+
19
+ ## Code of Conduct
20
+
21
+ By participating in this project, you agree to abide by our [Code of Conduct](CODE_OF_CONDUCT.md). Please read it to understand the expectations we have for everyone who contributes to this project.
22
+
23
+ ## 📢 A Quick Word
24
+ Right now we will not be accepting any Contributions that add non-essential commands to Auto-GPT.
25
+
26
+ However, you absolutely can still add these commands to Auto-GPT in the form of plugins. Please check out this [template](https://github.com/Significant-Gravitas/Auto-GPT-Plugin-Template).
27
+ > ⚠️ Plugin support is expected to ship within the week. You can follow PR #757 for more updates!
28
+
29
+ ## Getting Started
30
+
31
+ To start contributing, follow these steps:
32
+
33
+ 1. Fork the repository and clone your fork.
34
+ 2. Create a new branch for your changes (use a descriptive name, such as `fix-bug-123` or `add-new-feature`).
35
+ 3. Make your changes in the new branch.
36
+ 4. Test your changes thoroughly.
37
+ 5. Commit and push your changes to your fork.
38
+ 6. Create a pull request following the guidelines in the [Submitting Pull Requests](#submitting-pull-requests) section.
39
+
40
+ ## How to Contribute
41
+
42
+ ### Reporting Bugs
43
+
44
+ If you find a bug in the project, please create an issue on GitHub with the following information:
45
+
46
+ - A clear, descriptive title for the issue.
47
+ - A description of the problem, including steps to reproduce the issue.
48
+ - Any relevant logs, screenshots, or other supporting information.
49
+
50
+ ### Suggesting Enhancements
51
+
52
+ If you have an idea for a new feature or improvement, please create an issue on GitHub with the following information:
53
+
54
+ - A clear, descriptive title for the issue.
55
+ - A detailed description of the proposed enhancement, including any benefits and potential drawbacks.
56
+ - Any relevant examples, mockups, or supporting information.
57
+
58
+ ### Submitting Pull Requests
59
+
60
+ When submitting a pull request, please ensure that your changes meet the following criteria:
61
+
62
+ - Your pull request should be atomic and focus on a single change.
63
+ - Your pull request should include tests for your change.
64
+ - You should have thoroughly tested your changes with multiple different prompts.
65
+ - You should have considered potential risks and mitigations for your changes.
66
+ - You should have documented your changes clearly and comprehensively.
67
+ - You should not include any unrelated or "extra" small tweaks or changes.
68
+
69
+ ## Style Guidelines
70
+
71
+ ### Code Formatting
72
+
73
+ We use the `black` code formatter to maintain a consistent coding style across the project. Please ensure that your code is formatted using `black` before submitting a pull request. You can install `black` using `pip`:
74
+
75
+ ```bash
76
+ pip install black
77
+ ```
78
+
79
+ To format your code, run the following command in the project's root directory:
80
+
81
+ ```bash
82
+ black .
83
+ ```
84
+ ### Pre-Commit Hooks
85
+ We use pre-commit hooks to ensure that code formatting and other checks are performed automatically before each commit. To set up pre-commit hooks for this project, follow these steps:
86
+
87
+ Install the pre-commit package using pip:
88
+ ```bash
89
+ pip install pre-commit
90
+ ```
91
+
92
+ Run the following command in the project's root directory to install the pre-commit hooks:
93
+ ```bash
94
+ pre-commit install
95
+ ```
96
+
97
+ Now, the pre-commit hooks will run automatically before each commit, checking your code formatting and other requirements.
98
+
99
+ If you encounter any issues or have questions, feel free to reach out to the maintainers or open a new issue on GitHub. We're here to help and appreciate your efforts to contribute to the project.
100
+
101
+ Happy coding, and once again, thank you for your contributions!
102
+
103
+ Maintainers will look at PR that have no merge conflicts when deciding what to add to the project. Make sure your PR shows up here:
104
+
105
+ https://github.com/Torantulino/Auto-GPT/pulls?q=is%3Apr+is%3Aopen+-is%3Aconflict+
Dockerfile ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use an official Python base image from the Docker Hub
2
+ FROM python:3.10-slim
3
+
4
+ # Install git
5
+ RUN apt-get -y update
6
+ RUN apt-get -y install git chromium-driver
7
+
8
+ # Install Xvfb and other dependencies for headless browser testing
9
+ RUN apt-get update \
10
+ && apt-get install -y wget gnupg2 libgtk-3-0 libdbus-glib-1-2 dbus-x11 xvfb ca-certificates
11
+
12
+ # Install Firefox / Chromium
13
+ RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
14
+ && echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list \
15
+ && apt-get update \
16
+ && apt-get install -y chromium firefox-esr
17
+
18
+ # Set environment variables
19
+ ENV PIP_NO_CACHE_DIR=yes \
20
+ PYTHONUNBUFFERED=1 \
21
+ PYTHONDONTWRITEBYTECODE=1
22
+
23
+ # Create a non-root user and set permissions
24
+ RUN useradd --create-home appuser
25
+ WORKDIR /home/appuser
26
+ RUN chown appuser:appuser /home/appuser
27
+ USER appuser
28
+
29
+ # Copy the requirements.txt file and install the requirements
30
+ COPY --chown=appuser:appuser requirements.txt .
31
+ RUN sed -i '/Items below this point will not be included in the Docker Image/,$d' requirements.txt && \
32
+ pip install --no-cache-dir --user -r requirements.txt
33
+
34
+ # Copy the application files
35
+ COPY --chown=appuser:appuser autogpt/ ./autogpt
36
+
37
+ # Set the entrypoint
38
+ ENTRYPOINT ["python", "-m", "autogpt"]
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Toran Bruce Richards
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: AutoGPT
3
+ emoji: 🦾
4
+ colorFrom: yellow
5
+ colorTo: yellow
6
+ sdk: gradio
7
+ sdk_version: 3.27.0
8
+ app_file: ui/app.py
9
+ pinned: false
10
+ license: mit
11
+ duplicated_from: aliabid94/AutoGPT
12
+ ---
13
+
autogpt/__init__.py ADDED
File without changes
autogpt/__main__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Auto-GPT: A GPT powered AI Assistant"""
2
+ import autogpt.cli
3
+
4
+ if __name__ == "__main__":
5
+ autogpt.cli.main()
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,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from colorama import Fore, Style
2
+
3
+ from autogpt.app import execute_command, get_command
4
+ from autogpt.chat import chat_with_ai, create_chat_message
5
+ from autogpt.config import Config
6
+ from autogpt.json_utils.json_fix_llm import fix_json_using_multiple_techniques
7
+ from autogpt.json_utils.utilities import validate_json
8
+ from autogpt.logs import logger, print_assistant_thoughts
9
+ from autogpt.speech import say_text
10
+ from autogpt.spinner import Spinner
11
+ from autogpt.utils import clean_input
12
+
13
+
14
+ class Agent:
15
+ """Agent class for interacting with Auto-GPT.
16
+
17
+ Attributes:
18
+ ai_name: The name of the agent.
19
+ memory: The memory object to use.
20
+ full_message_history: The full message history.
21
+ next_action_count: The number of actions to execute.
22
+ system_prompt: The system prompt is the initial prompt that defines everything the AI needs to know to achieve its task successfully.
23
+ Currently, the dynamic and customizable information in the system prompt are ai_name, description and goals.
24
+
25
+ triggering_prompt: The last sentence the AI will see before answering. For Auto-GPT, this prompt is:
26
+ Determine which next command to use, and respond using the format specified above:
27
+ The triggering prompt is not part of the system prompt because between the system prompt and the triggering
28
+ prompt we have contextual information that can distract the AI and make it forget that its goal is to find the next task to achieve.
29
+ SYSTEM PROMPT
30
+ CONTEXTUAL INFORMATION (memory, previous conversations, anything relevant)
31
+ TRIGGERING PROMPT
32
+
33
+ The triggering prompt reminds the AI about its short term meta task (defining the next task)
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ ai_name,
39
+ memory,
40
+ full_message_history,
41
+ next_action_count,
42
+ system_prompt,
43
+ triggering_prompt,
44
+ ):
45
+ self.ai_name = ai_name
46
+ self.memory = memory
47
+ self.full_message_history = full_message_history
48
+ self.next_action_count = next_action_count
49
+ self.system_prompt = system_prompt
50
+ self.triggering_prompt = triggering_prompt
51
+
52
+ def start_interaction_loop(self):
53
+ # Interaction Loop
54
+ cfg = Config()
55
+ loop_count = 0
56
+ command_name = None
57
+ arguments = None
58
+ user_input = ""
59
+
60
+ while True:
61
+ # Discontinue if continuous limit is reached
62
+ loop_count += 1
63
+ if (
64
+ cfg.continuous_mode
65
+ and cfg.continuous_limit > 0
66
+ and loop_count > cfg.continuous_limit
67
+ ):
68
+ logger.typewriter_log(
69
+ "Continuous Limit Reached: ", Fore.YELLOW, f"{cfg.continuous_limit}"
70
+ )
71
+ break
72
+
73
+ # Send message to AI, get response
74
+ with Spinner("Thinking... "):
75
+ assistant_reply = chat_with_ai(
76
+ self.system_prompt,
77
+ self.triggering_prompt,
78
+ self.full_message_history,
79
+ self.memory,
80
+ cfg.fast_token_limit,
81
+ ) # TODO: This hardcodes the model to use GPT3.5. Make this an argument
82
+
83
+ assistant_reply_json = fix_json_using_multiple_techniques(assistant_reply)
84
+
85
+ # Print Assistant thoughts
86
+ if assistant_reply_json != {}:
87
+ validate_json(assistant_reply_json, "llm_response_format_1")
88
+ # Get command name and arguments
89
+ try:
90
+ print_assistant_thoughts(self.ai_name, assistant_reply_json)
91
+ command_name, arguments = get_command(assistant_reply_json)
92
+ # command_name, arguments = assistant_reply_json_valid["command"]["name"], assistant_reply_json_valid["command"]["args"]
93
+ if cfg.speak_mode:
94
+ say_text(f"I want to execute {command_name}")
95
+ except Exception as e:
96
+ logger.error("Error: \n", str(e))
97
+
98
+ if not cfg.continuous_mode and self.next_action_count == 0:
99
+ ### GET USER AUTHORIZATION TO EXECUTE COMMAND ###
100
+ # Get key press: Prompt the user to press enter to continue or escape
101
+ # to exit
102
+ logger.typewriter_log(
103
+ "NEXT ACTION: ",
104
+ Fore.CYAN,
105
+ f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} "
106
+ f"ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}",
107
+ )
108
+ print(
109
+ "Enter 'y' to authorise command, 'y -N' to run N continuous "
110
+ "commands, 'n' to exit program, or enter feedback for "
111
+ f"{self.ai_name}...",
112
+ flush=True,
113
+ )
114
+ while True:
115
+ console_input = clean_input(
116
+ Fore.MAGENTA + "Input:" + Style.RESET_ALL
117
+ )
118
+ if console_input.lower().strip() == "y":
119
+ user_input = "GENERATE NEXT COMMAND JSON"
120
+ break
121
+ elif console_input.lower().strip() == "":
122
+ print("Invalid input format.")
123
+ continue
124
+ elif console_input.lower().startswith("y -"):
125
+ try:
126
+ self.next_action_count = abs(
127
+ int(console_input.split(" ")[1])
128
+ )
129
+ user_input = "GENERATE NEXT COMMAND JSON"
130
+ except ValueError:
131
+ print(
132
+ "Invalid input format. Please enter 'y -n' where n is"
133
+ " the number of continuous tasks."
134
+ )
135
+ continue
136
+ break
137
+ elif console_input.lower() == "n":
138
+ user_input = "EXIT"
139
+ break
140
+ else:
141
+ user_input = console_input
142
+ command_name = "human_feedback"
143
+ break
144
+
145
+ if user_input == "GENERATE NEXT COMMAND JSON":
146
+ logger.typewriter_log(
147
+ "-=-=-=-=-=-=-= COMMAND AUTHORISED BY USER -=-=-=-=-=-=-=",
148
+ Fore.MAGENTA,
149
+ "",
150
+ )
151
+ elif user_input == "EXIT":
152
+ print("Exiting...", flush=True)
153
+ break
154
+ else:
155
+ # Print command
156
+ logger.typewriter_log(
157
+ "NEXT ACTION: ",
158
+ Fore.CYAN,
159
+ f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL}"
160
+ f" ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}",
161
+ )
162
+
163
+ # Execute command
164
+ if command_name is not None and command_name.lower().startswith("error"):
165
+ result = (
166
+ f"Command {command_name} threw the following error: {arguments}"
167
+ )
168
+ elif command_name == "human_feedback":
169
+ result = f"Human feedback: {user_input}"
170
+ else:
171
+ result = (
172
+ f"Command {command_name} returned: "
173
+ f"{execute_command(command_name, arguments)}"
174
+ )
175
+ if self.next_action_count > 0:
176
+ self.next_action_count -= 1
177
+
178
+ memory_to_add = (
179
+ f"Assistant Reply: {assistant_reply} "
180
+ f"\nResult: {result} "
181
+ f"\nHuman Feedback: {user_input} "
182
+ )
183
+
184
+ self.memory.add(memory_to_add)
185
+
186
+ # Check if there's a result from the command append it to the message
187
+ # history
188
+ if result is not None:
189
+ self.full_message_history.append(create_chat_message("system", result))
190
+ logger.typewriter_log("SYSTEM: ", Fore.YELLOW, result)
191
+ else:
192
+ self.full_message_history.append(
193
+ create_chat_message("system", "Unable to execute command")
194
+ )
195
+ logger.typewriter_log(
196
+ "SYSTEM: ", Fore.YELLOW, "Unable to execute command"
197
+ )
autogpt/agent/agent_manager.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Agent manager for managing GPT agents"""
2
+ from __future__ import annotations
3
+
4
+ from typing import Union
5
+
6
+ from autogpt.config.config import Singleton
7
+ from autogpt.llm_utils import create_chat_completion
8
+
9
+
10
+ class AgentManager(metaclass=Singleton):
11
+ """Agent manager for managing GPT agents"""
12
+
13
+ def __init__(self):
14
+ self.next_key = 0
15
+ self.agents = {} # key, (task, full_message_history, model)
16
+
17
+ # Create new GPT agent
18
+ # TODO: Centralise use of create_chat_completion() to globally enforce token limit
19
+
20
+ def create_agent(self, task: str, prompt: str, model: str) -> tuple[int, str]:
21
+ """Create a new agent and return its key
22
+
23
+ Args:
24
+ task: The task to perform
25
+ prompt: The prompt to use
26
+ model: The model to use
27
+
28
+ Returns:
29
+ The key of the new agent
30
+ """
31
+ messages = [
32
+ {"role": "user", "content": prompt},
33
+ ]
34
+
35
+ # Start GPT instance
36
+ agent_reply = create_chat_completion(
37
+ model=model,
38
+ messages=messages,
39
+ )
40
+
41
+ # Update full message history
42
+ messages.append({"role": "assistant", "content": agent_reply})
43
+
44
+ key = self.next_key
45
+ # This is done instead of len(agents) to make keys unique even if agents
46
+ # are deleted
47
+ self.next_key += 1
48
+
49
+ self.agents[key] = (task, messages, model)
50
+
51
+ return key, agent_reply
52
+
53
+ def message_agent(self, key: str | int, message: str) -> str:
54
+ """Send a message to an agent and return its response
55
+
56
+ Args:
57
+ key: The key of the agent to message
58
+ message: The message to send to the agent
59
+
60
+ Returns:
61
+ The agent's response
62
+ """
63
+ task, messages, model = self.agents[int(key)]
64
+
65
+ # Add user message to message history before sending to agent
66
+ messages.append({"role": "user", "content": message})
67
+
68
+ # Start GPT instance
69
+ agent_reply = create_chat_completion(
70
+ model=model,
71
+ messages=messages,
72
+ )
73
+
74
+ # Update full message history
75
+ messages.append({"role": "assistant", "content": agent_reply})
76
+
77
+ return agent_reply
78
+
79
+ def list_agents(self) -> list[tuple[str | int, str]]:
80
+ """Return a list of all agents
81
+
82
+ Returns:
83
+ A list of tuples of the form (key, task)
84
+ """
85
+
86
+ # Return a list of agent keys and their tasks
87
+ return [(key, task) for key, (task, _, _) in self.agents.items()]
88
+
89
+ def delete_agent(self, key: Union[str, int]) -> bool:
90
+ """Delete an agent from the agent manager
91
+
92
+ Args:
93
+ key: The key of the agent to delete
94
+
95
+ Returns:
96
+ True if successful, False otherwise
97
+ """
98
+
99
+ try:
100
+ del self.agents[int(key)]
101
+ return True
102
+ except KeyError:
103
+ return False
autogpt/app.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Command and Control """
2
+ import json
3
+ from typing import Dict, List, NoReturn, Union
4
+
5
+ from autogpt.agent.agent_manager import AgentManager
6
+ from autogpt.commands.analyze_code import analyze_code
7
+ from autogpt.commands.audio_text import read_audio_from_file
8
+ from autogpt.commands.execute_code import (
9
+ execute_python_file,
10
+ execute_shell,
11
+ execute_shell_popen,
12
+ )
13
+ from autogpt.commands.file_operations import (
14
+ append_to_file,
15
+ delete_file,
16
+ download_file,
17
+ read_file,
18
+ search_files,
19
+ write_to_file,
20
+ )
21
+ from autogpt.commands.git_operations import clone_repository
22
+ from autogpt.commands.google_search import google_official_search, google_search
23
+ from autogpt.commands.image_gen import generate_image
24
+ from autogpt.commands.improve_code import improve_code
25
+ from autogpt.commands.twitter import send_tweet
26
+ from autogpt.commands.web_requests import scrape_links, scrape_text
27
+ from autogpt.commands.web_selenium import browse_website
28
+ from autogpt.commands.write_tests import write_tests
29
+ from autogpt.config import Config
30
+ from autogpt.json_utils.json_fix_llm import fix_and_parse_json
31
+ from autogpt.memory import get_memory
32
+ from autogpt.processing.text import summarize_text
33
+ from autogpt.speech import say_text
34
+
35
+ CFG = Config()
36
+ AGENT_MANAGER = AgentManager()
37
+
38
+
39
+ def is_valid_int(value: str) -> bool:
40
+ """Check if the value is a valid integer
41
+
42
+ Args:
43
+ value (str): The value to check
44
+
45
+ Returns:
46
+ bool: True if the value is a valid integer, False otherwise
47
+ """
48
+ try:
49
+ int(value)
50
+ return True
51
+ except ValueError:
52
+ return False
53
+
54
+
55
+ def get_command(response_json: Dict):
56
+ """Parse the response and return the command name and arguments
57
+
58
+ Args:
59
+ response_json (json): The response from the AI
60
+
61
+ Returns:
62
+ tuple: The command name and arguments
63
+
64
+ Raises:
65
+ json.decoder.JSONDecodeError: If the response is not valid JSON
66
+
67
+ Exception: If any other error occurs
68
+ """
69
+ try:
70
+ if "command" not in response_json:
71
+ return "Error:", "Missing 'command' object in JSON"
72
+
73
+ if not isinstance(response_json, dict):
74
+ return "Error:", f"'response_json' object is not dictionary {response_json}"
75
+
76
+ command = response_json["command"]
77
+ if not isinstance(command, dict):
78
+ return "Error:", "'command' object is not a dictionary"
79
+
80
+ if "name" not in command:
81
+ return "Error:", "Missing 'name' field in 'command' object"
82
+
83
+ command_name = command["name"]
84
+
85
+ # Use an empty dictionary if 'args' field is not present in 'command' object
86
+ arguments = command.get("args", {})
87
+
88
+ return command_name, arguments
89
+ except json.decoder.JSONDecodeError:
90
+ return "Error:", "Invalid JSON"
91
+ # All other errors, return "Error: + error message"
92
+ except Exception as e:
93
+ return "Error:", str(e)
94
+
95
+
96
+ def map_command_synonyms(command_name: str):
97
+ """Takes the original command name given by the AI, and checks if the
98
+ string matches a list of common/known hallucinations
99
+ """
100
+ synonyms = [
101
+ ("write_file", "write_to_file"),
102
+ ("create_file", "write_to_file"),
103
+ ("search", "google"),
104
+ ]
105
+ for seen_command, actual_command_name in synonyms:
106
+ if command_name == seen_command:
107
+ return actual_command_name
108
+ return command_name
109
+
110
+
111
+ def execute_command(command_name: str, arguments):
112
+ """Execute the command and return the result
113
+
114
+ Args:
115
+ command_name (str): The name of the command to execute
116
+ arguments (dict): The arguments for the command
117
+
118
+ Returns:
119
+ str: The result of the command
120
+ """
121
+ try:
122
+ command_name = map_command_synonyms(command_name.lower())
123
+ if command_name == "google":
124
+ # Check if the Google API key is set and use the official search method
125
+ # If the API key is not set or has only whitespaces, use the unofficial
126
+ # search method
127
+ key = CFG.google_api_key
128
+ if key and key.strip() and key != "your-google-api-key":
129
+ google_result = google_official_search(arguments["input"])
130
+ return google_result
131
+ else:
132
+ google_result = google_search(arguments["input"])
133
+
134
+ # google_result can be a list or a string depending on the search results
135
+ if isinstance(google_result, list):
136
+ safe_message = [
137
+ google_result_single.encode("utf-8", "ignore")
138
+ for google_result_single in google_result
139
+ ]
140
+ else:
141
+ safe_message = google_result.encode("utf-8", "ignore")
142
+
143
+ return safe_message.decode("utf-8")
144
+ elif command_name == "memory_add":
145
+ memory = get_memory(CFG)
146
+ return memory.add(arguments["string"])
147
+ elif command_name == "start_agent":
148
+ return start_agent(
149
+ arguments["name"], arguments["task"], arguments["prompt"]
150
+ )
151
+ elif command_name == "message_agent":
152
+ return message_agent(arguments["key"], arguments["message"])
153
+ elif command_name == "list_agents":
154
+ return list_agents()
155
+ elif command_name == "delete_agent":
156
+ return delete_agent(arguments["key"])
157
+ elif command_name == "get_text_summary":
158
+ return get_text_summary(arguments["url"], arguments["question"])
159
+ elif command_name == "get_hyperlinks":
160
+ return get_hyperlinks(arguments["url"])
161
+ elif command_name == "clone_repository":
162
+ return clone_repository(
163
+ arguments["repository_url"], arguments["clone_path"]
164
+ )
165
+ elif command_name == "read_file":
166
+ return read_file(arguments["file"])
167
+ elif command_name == "write_to_file":
168
+ return write_to_file(arguments["file"], arguments["text"])
169
+ elif command_name == "append_to_file":
170
+ return append_to_file(arguments["file"], arguments["text"])
171
+ elif command_name == "delete_file":
172
+ return delete_file(arguments["file"])
173
+ elif command_name == "search_files":
174
+ return search_files(arguments["directory"])
175
+ elif command_name == "download_file":
176
+ if not CFG.allow_downloads:
177
+ return "Error: You do not have user authorization to download files locally."
178
+ return download_file(arguments["url"], arguments["file"])
179
+ elif command_name == "browse_website":
180
+ return browse_website(arguments["url"], arguments["question"])
181
+ # TODO: Change these to take in a file rather than pasted code, if
182
+ # non-file is given, return instructions "Input should be a python
183
+ # filepath, write your code to file and try again"
184
+ elif command_name == "analyze_code":
185
+ return analyze_code(arguments["code"])
186
+ elif command_name == "improve_code":
187
+ return improve_code(arguments["suggestions"], arguments["code"])
188
+ elif command_name == "write_tests":
189
+ return write_tests(arguments["code"], arguments.get("focus"))
190
+ elif command_name == "execute_python_file": # Add this command
191
+ return execute_python_file(arguments["file"])
192
+ elif command_name == "execute_shell":
193
+ if CFG.execute_local_commands:
194
+ return execute_shell(arguments["command_line"])
195
+ else:
196
+ return (
197
+ "You are not allowed to run local shell commands. To execute"
198
+ " shell commands, EXECUTE_LOCAL_COMMANDS must be set to 'True' "
199
+ "in your config. Do not attempt to bypass the restriction."
200
+ )
201
+ elif command_name == "execute_shell_popen":
202
+ if CFG.execute_local_commands:
203
+ return execute_shell_popen(arguments["command_line"])
204
+ else:
205
+ return (
206
+ "You are not allowed to run local shell commands. To execute"
207
+ " shell commands, EXECUTE_LOCAL_COMMANDS must be set to 'True' "
208
+ "in your config. Do not attempt to bypass the restriction."
209
+ )
210
+ elif command_name == "read_audio_from_file":
211
+ return read_audio_from_file(arguments["file"])
212
+ elif command_name == "generate_image":
213
+ return generate_image(arguments["prompt"])
214
+ elif command_name == "send_tweet":
215
+ return send_tweet(arguments["text"])
216
+ elif command_name == "do_nothing":
217
+ return "No action performed."
218
+ elif command_name == "task_complete":
219
+ shutdown()
220
+ else:
221
+ return (
222
+ f"Unknown command '{command_name}'. Please refer to the 'COMMANDS'"
223
+ " list for available commands and only respond in the specified JSON"
224
+ " format."
225
+ )
226
+ except Exception as e:
227
+ return f"Error: {str(e)}"
228
+
229
+
230
+ def get_text_summary(url: str, question: str) -> str:
231
+ """Return the results of a Google search
232
+
233
+ Args:
234
+ url (str): The url to scrape
235
+ question (str): The question to summarize the text for
236
+
237
+ Returns:
238
+ str: The summary of the text
239
+ """
240
+ text = scrape_text(url)
241
+ summary = summarize_text(url, text, question)
242
+ return f""" "Result" : {summary}"""
243
+
244
+
245
+ def get_hyperlinks(url: str) -> Union[str, List[str]]:
246
+ """Return the results of a Google search
247
+
248
+ Args:
249
+ url (str): The url to scrape
250
+
251
+ Returns:
252
+ str or list: The hyperlinks on the page
253
+ """
254
+ return scrape_links(url)
255
+
256
+
257
+ def shutdown() -> NoReturn:
258
+ """Shut down the program"""
259
+ print("Shutting down...")
260
+ quit()
261
+
262
+
263
+ def start_agent(name: str, task: str, prompt: str, model=CFG.fast_llm_model) -> str:
264
+ """Start an agent with a given name, task, and prompt
265
+
266
+ Args:
267
+ name (str): The name of the agent
268
+ task (str): The task of the agent
269
+ prompt (str): The prompt for the agent
270
+ model (str): The model to use for the agent
271
+
272
+ Returns:
273
+ str: The response of the agent
274
+ """
275
+ # Remove underscores from name
276
+ voice_name = name.replace("_", " ")
277
+
278
+ first_message = f"""You are {name}. Respond with: "Acknowledged"."""
279
+ agent_intro = f"{voice_name} here, Reporting for duty!"
280
+
281
+ # Create agent
282
+ if CFG.speak_mode:
283
+ say_text(agent_intro, 1)
284
+ key, ack = AGENT_MANAGER.create_agent(task, first_message, model)
285
+
286
+ if CFG.speak_mode:
287
+ say_text(f"Hello {voice_name}. Your task is as follows. {task}.")
288
+
289
+ # Assign task (prompt), get response
290
+ agent_response = AGENT_MANAGER.message_agent(key, prompt)
291
+
292
+ return f"Agent {name} created with key {key}. First response: {agent_response}"
293
+
294
+
295
+ def message_agent(key: str, message: str) -> str:
296
+ """Message an agent with a given key and message"""
297
+ # Check if the key is a valid integer
298
+ if is_valid_int(key):
299
+ agent_response = AGENT_MANAGER.message_agent(int(key), message)
300
+ else:
301
+ return "Invalid key, must be an integer."
302
+
303
+ # Speak response
304
+ if CFG.speak_mode:
305
+ say_text(agent_response, 1)
306
+ return agent_response
307
+
308
+
309
+ def list_agents():
310
+ """List all agents
311
+
312
+ Returns:
313
+ str: A list of all agents
314
+ """
315
+ return "List of agents:\n" + "\n".join(
316
+ [str(x[0]) + ": " + x[1] for x in AGENT_MANAGER.list_agents()]
317
+ )
318
+
319
+
320
+ def delete_agent(key: str) -> str:
321
+ """Delete an agent with a given key
322
+
323
+ Args:
324
+ key (str): The key of the agent to delete
325
+
326
+ Returns:
327
+ str: A message indicating whether the agent was deleted or not
328
+ """
329
+ result = AGENT_MANAGER.delete_agent(key)
330
+ return f"Agent {key} deleted." if result else f"Agent {key} does not exist."
autogpt/chat.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+
3
+ from openai.error import RateLimitError
4
+
5
+ from autogpt import token_counter
6
+ from autogpt.config import Config
7
+ from autogpt.llm_utils import create_chat_completion
8
+ from autogpt.logs import logger
9
+
10
+ cfg = Config()
11
+
12
+
13
+ def create_chat_message(role, content):
14
+ """
15
+ Create a chat message with the given role and content.
16
+
17
+ Args:
18
+ role (str): The role of the message sender, e.g., "system", "user", or "assistant".
19
+ content (str): The content of the message.
20
+
21
+ Returns:
22
+ dict: A dictionary containing the role and content of the message.
23
+ """
24
+ return {"role": role, "content": content}
25
+
26
+
27
+ def generate_context(prompt, relevant_memory, full_message_history, model):
28
+ current_context = [
29
+ create_chat_message("system", prompt),
30
+ create_chat_message(
31
+ "system", f"The current time and date is {time.strftime('%c')}"
32
+ ),
33
+ create_chat_message(
34
+ "system",
35
+ f"This reminds you of these events from your past:\n{relevant_memory}\n\n",
36
+ ),
37
+ ]
38
+
39
+ # Add messages from the full message history until we reach the token limit
40
+ next_message_to_add_index = len(full_message_history) - 1
41
+ insertion_index = len(current_context)
42
+ # Count the currently used tokens
43
+ current_tokens_used = token_counter.count_message_tokens(current_context, model)
44
+ return (
45
+ next_message_to_add_index,
46
+ current_tokens_used,
47
+ insertion_index,
48
+ current_context,
49
+ )
50
+
51
+
52
+ # TODO: Change debug from hardcode to argument
53
+ def chat_with_ai(
54
+ prompt, user_input, full_message_history, permanent_memory, token_limit
55
+ ):
56
+ """Interact with the OpenAI API, sending the prompt, user input, message history,
57
+ and permanent memory."""
58
+ while True:
59
+ try:
60
+ """
61
+ Interact with the OpenAI API, sending the prompt, user input,
62
+ message history, and permanent memory.
63
+
64
+ Args:
65
+ prompt (str): The prompt explaining the rules to the AI.
66
+ user_input (str): The input from the user.
67
+ full_message_history (list): The list of all messages sent between the
68
+ user and the AI.
69
+ permanent_memory (Obj): The memory object containing the permanent
70
+ memory.
71
+ token_limit (int): The maximum number of tokens allowed in the API call.
72
+
73
+ Returns:
74
+ str: The AI's response.
75
+ """
76
+ model = cfg.fast_llm_model # TODO: Change model from hardcode to argument
77
+ # Reserve 1000 tokens for the response
78
+
79
+ logger.debug(f"Token limit: {token_limit}")
80
+ send_token_limit = token_limit - 1000
81
+
82
+ relevant_memory = (
83
+ ""
84
+ if len(full_message_history) == 0
85
+ else permanent_memory.get_relevant(str(full_message_history[-9:]), 10)
86
+ )
87
+
88
+ logger.debug(f"Memory Stats: {permanent_memory.get_stats()}")
89
+
90
+ (
91
+ next_message_to_add_index,
92
+ current_tokens_used,
93
+ insertion_index,
94
+ current_context,
95
+ ) = generate_context(prompt, relevant_memory, full_message_history, model)
96
+
97
+ while current_tokens_used > 2500:
98
+ # remove memories until we are under 2500 tokens
99
+ relevant_memory = relevant_memory[:-1]
100
+ (
101
+ next_message_to_add_index,
102
+ current_tokens_used,
103
+ insertion_index,
104
+ current_context,
105
+ ) = generate_context(
106
+ prompt, relevant_memory, full_message_history, model
107
+ )
108
+
109
+ current_tokens_used += token_counter.count_message_tokens(
110
+ [create_chat_message("user", user_input)], model
111
+ ) # Account for user input (appended later)
112
+
113
+ while next_message_to_add_index >= 0:
114
+ # print (f"CURRENT TOKENS USED: {current_tokens_used}")
115
+ message_to_add = full_message_history[next_message_to_add_index]
116
+
117
+ tokens_to_add = token_counter.count_message_tokens(
118
+ [message_to_add], model
119
+ )
120
+ if current_tokens_used + tokens_to_add > send_token_limit:
121
+ break
122
+
123
+ # Add the most recent message to the start of the current context,
124
+ # after the two system prompts.
125
+ current_context.insert(
126
+ insertion_index, full_message_history[next_message_to_add_index]
127
+ )
128
+
129
+ # Count the currently used tokens
130
+ current_tokens_used += tokens_to_add
131
+
132
+ # Move to the next most recent message in the full message history
133
+ next_message_to_add_index -= 1
134
+
135
+ # Append user input, the length of this is accounted for above
136
+ current_context.extend([create_chat_message("user", user_input)])
137
+
138
+ # Calculate remaining tokens
139
+ tokens_remaining = token_limit - current_tokens_used
140
+ # assert tokens_remaining >= 0, "Tokens remaining is negative.
141
+ # This should never happen, please submit a bug report at
142
+ # https://www.github.com/Torantulino/Auto-GPT"
143
+
144
+ # Debug print the current context
145
+ logger.debug(f"Token limit: {token_limit}")
146
+ logger.debug(f"Send Token Count: {current_tokens_used}")
147
+ logger.debug(f"Tokens remaining for response: {tokens_remaining}")
148
+ logger.debug("------------ CONTEXT SENT TO AI ---------------")
149
+ for message in current_context:
150
+ # Skip printing the prompt
151
+ if message["role"] == "system" and message["content"] == prompt:
152
+ continue
153
+ logger.debug(f"{message['role'].capitalize()}: {message['content']}")
154
+ logger.debug("")
155
+ logger.debug("----------- END OF CONTEXT ----------------")
156
+
157
+ # TODO: use a model defined elsewhere, so that model can contain
158
+ # temperature and other settings we care about
159
+ assistant_reply = create_chat_completion(
160
+ model=model,
161
+ messages=current_context,
162
+ max_tokens=tokens_remaining,
163
+ )
164
+
165
+ # Update full message history
166
+ full_message_history.append(create_chat_message("user", user_input))
167
+ full_message_history.append(
168
+ create_chat_message("assistant", assistant_reply)
169
+ )
170
+
171
+ return assistant_reply
172
+ except RateLimitError:
173
+ # TODO: When we switch to langchain, this is built in
174
+ print("Error: ", "API Rate Limit Reached. Waiting 10 seconds...")
175
+ time.sleep(10)
autogpt/cli.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Main script for the autogpt package."""
2
+ import click
3
+
4
+
5
+ @click.group(invoke_without_command=True)
6
+ @click.option("-c", "--continuous", is_flag=True, help="Enable Continuous Mode")
7
+ @click.option(
8
+ "--skip-reprompt",
9
+ "-y",
10
+ is_flag=True,
11
+ help="Skips the re-prompting messages at the beginning of the script",
12
+ )
13
+ @click.option(
14
+ "--ai-settings",
15
+ "-C",
16
+ help="Specifies which ai_settings.yaml file to use, will also automatically skip the re-prompt.",
17
+ )
18
+ @click.option(
19
+ "-l",
20
+ "--continuous-limit",
21
+ type=int,
22
+ help="Defines the number of times to run in continuous mode",
23
+ )
24
+ @click.option("--speak", is_flag=True, help="Enable Speak Mode")
25
+ @click.option("--debug", is_flag=True, help="Enable Debug Mode")
26
+ @click.option("--gpt3only", is_flag=True, help="Enable GPT3.5 Only Mode")
27
+ @click.option("--gpt4only", is_flag=True, help="Enable GPT4 Only Mode")
28
+ @click.option(
29
+ "--use-memory",
30
+ "-m",
31
+ "memory_type",
32
+ type=str,
33
+ help="Defines which Memory backend to use",
34
+ )
35
+ @click.option(
36
+ "-b",
37
+ "--browser-name",
38
+ help="Specifies which web-browser to use when using selenium to scrape the web.",
39
+ )
40
+ @click.option(
41
+ "--allow-downloads",
42
+ is_flag=True,
43
+ help="Dangerous: Allows Auto-GPT to download files natively.",
44
+ )
45
+ @click.option(
46
+ "--skip-news",
47
+ is_flag=True,
48
+ help="Specifies whether to suppress the output of latest news on startup.",
49
+ )
50
+ @click.pass_context
51
+ def main(
52
+ ctx: click.Context,
53
+ continuous: bool,
54
+ continuous_limit: int,
55
+ ai_settings: str,
56
+ skip_reprompt: bool,
57
+ speak: bool,
58
+ debug: bool,
59
+ gpt3only: bool,
60
+ gpt4only: bool,
61
+ memory_type: str,
62
+ browser_name: str,
63
+ allow_downloads: bool,
64
+ skip_news: bool,
65
+ ) -> None:
66
+ """
67
+ Welcome to AutoGPT an experimental open-source application showcasing the capabilities of the GPT-4 pushing the boundaries of AI.
68
+
69
+ Start an Auto-GPT assistant.
70
+ """
71
+ # Put imports inside function to avoid importing everything when starting the CLI
72
+ import logging
73
+
74
+ from colorama import Fore
75
+
76
+ from autogpt.agent.agent import Agent
77
+ from autogpt.config import Config, check_openai_api_key
78
+ from autogpt.configurator import create_config
79
+ from autogpt.logs import logger
80
+ from autogpt.memory import get_memory
81
+ from autogpt.prompt import construct_prompt
82
+ from autogpt.utils import get_current_git_branch, get_latest_bulletin
83
+
84
+ if ctx.invoked_subcommand is None:
85
+ cfg = Config()
86
+ # TODO: fill in llm values here
87
+ check_openai_api_key()
88
+ create_config(
89
+ continuous,
90
+ continuous_limit,
91
+ ai_settings,
92
+ skip_reprompt,
93
+ speak,
94
+ debug,
95
+ gpt3only,
96
+ gpt4only,
97
+ memory_type,
98
+ browser_name,
99
+ allow_downloads,
100
+ skip_news,
101
+ )
102
+ logger.set_level(logging.DEBUG if cfg.debug_mode else logging.INFO)
103
+ ai_name = ""
104
+ if not cfg.skip_news:
105
+ motd = get_latest_bulletin()
106
+ if motd:
107
+ logger.typewriter_log("NEWS: ", Fore.GREEN, motd)
108
+ git_branch = get_current_git_branch()
109
+ if git_branch and git_branch != "stable":
110
+ logger.typewriter_log(
111
+ "WARNING: ",
112
+ Fore.RED,
113
+ f"You are running on `{git_branch}` branch "
114
+ "- this is not a supported branch.",
115
+ )
116
+ system_prompt = construct_prompt()
117
+ # print(prompt)
118
+ # Initialize variables
119
+ full_message_history = []
120
+ next_action_count = 0
121
+ # Make a constant:
122
+ triggering_prompt = (
123
+ "Determine which next command to use, and respond using the"
124
+ " format specified above:"
125
+ )
126
+ # Initialize memory and make sure it is empty.
127
+ # this is particularly important for indexing and referencing pinecone memory
128
+ memory = get_memory(cfg, init=True)
129
+ logger.typewriter_log(
130
+ "Using memory of type:", Fore.GREEN, f"{memory.__class__.__name__}"
131
+ )
132
+ logger.typewriter_log("Using Browser:", Fore.GREEN, cfg.selenium_web_browser)
133
+ agent = Agent(
134
+ ai_name=ai_name,
135
+ memory=memory,
136
+ full_message_history=full_message_history,
137
+ next_action_count=next_action_count,
138
+ system_prompt=system_prompt,
139
+ triggering_prompt=triggering_prompt,
140
+ )
141
+ agent.start_interaction_loop()
142
+
143
+
144
+ if __name__ == "__main__":
145
+ main()
autogpt/commands/__init__.py ADDED
File without changes
autogpt/commands/analyze_code.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Code evaluation module."""
2
+ from __future__ import annotations
3
+
4
+ from autogpt.llm_utils import call_ai_function
5
+
6
+
7
+ def analyze_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/audio_text.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+
3
+ import requests
4
+
5
+ from autogpt.config import Config
6
+ from autogpt.workspace import path_in_workspace
7
+
8
+ cfg = Config()
9
+
10
+
11
+ def read_audio_from_file(audio_path):
12
+ audio_path = path_in_workspace(audio_path)
13
+ with open(audio_path, "rb") as audio_file:
14
+ audio = audio_file.read()
15
+ return read_audio(audio)
16
+
17
+
18
+ def read_audio(audio):
19
+ model = cfg.huggingface_audio_to_text_model
20
+ api_url = f"https://api-inference.huggingface.co/models/{model}"
21
+ api_token = cfg.huggingface_api_token
22
+ headers = {"Authorization": f"Bearer {api_token}"}
23
+
24
+ if api_token is None:
25
+ raise ValueError(
26
+ "You need to set your Hugging Face API token in the config file."
27
+ )
28
+
29
+ response = requests.post(
30
+ api_url,
31
+ headers=headers,
32
+ data=audio,
33
+ )
34
+
35
+ text = json.loads(response.content.decode("utf-8"))["text"]
36
+ return "The audio says: " + text
autogpt/commands/execute_code.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Execute code in a Docker container"""
2
+ import os
3
+ import subprocess
4
+
5
+ import docker
6
+ from docker.errors import ImageNotFound
7
+
8
+ from autogpt.workspace import WORKSPACE_PATH, path_in_workspace
9
+
10
+
11
+ def execute_python_file(file: str) -> str:
12
+ """Execute a Python file in a Docker container and return the output
13
+
14
+ Args:
15
+ file (str): The name of the file to execute
16
+
17
+ Returns:
18
+ str: The output of the file
19
+ """
20
+
21
+ print(f"Executing file '{file}' in workspace '{WORKSPACE_PATH}'")
22
+
23
+ if not file.endswith(".py"):
24
+ return "Error: Invalid file type. Only .py files are allowed."
25
+
26
+ file_path = path_in_workspace(file)
27
+
28
+ if not os.path.isfile(file_path):
29
+ return f"Error: File '{file}' does not exist."
30
+
31
+ if we_are_running_in_a_docker_container():
32
+ result = subprocess.run(
33
+ f"python {file_path}", capture_output=True, encoding="utf8", shell=True
34
+ )
35
+ if result.returncode == 0:
36
+ return result.stdout
37
+ else:
38
+ return f"Error: {result.stderr}"
39
+
40
+ try:
41
+ client = docker.from_env()
42
+
43
+ # You can replace this with the desired Python image/version
44
+ # You can find available Python images on Docker Hub:
45
+ # https://hub.docker.com/_/python
46
+ image_name = "python:3-alpine"
47
+ try:
48
+ client.images.get(image_name)
49
+ print(f"Image '{image_name}' found locally")
50
+ except ImageNotFound:
51
+ print(f"Image '{image_name}' not found locally, pulling from Docker Hub")
52
+ # Use the low-level API to stream the pull response
53
+ low_level_client = docker.APIClient()
54
+ for line in low_level_client.pull(image_name, stream=True, decode=True):
55
+ # Print the status and progress, if available
56
+ status = line.get("status")
57
+ progress = line.get("progress")
58
+ if status and progress:
59
+ print(f"{status}: {progress}")
60
+ elif status:
61
+ print(status)
62
+
63
+ container = client.containers.run(
64
+ image_name,
65
+ f"python {file}",
66
+ volumes={
67
+ os.path.abspath(WORKSPACE_PATH): {
68
+ "bind": "/workspace",
69
+ "mode": "ro",
70
+ }
71
+ },
72
+ working_dir="/workspace",
73
+ stderr=True,
74
+ stdout=True,
75
+ detach=True,
76
+ )
77
+
78
+ container.wait()
79
+ logs = container.logs().decode("utf-8")
80
+ container.remove()
81
+
82
+ # print(f"Execution complete. Output: {output}")
83
+ # print(f"Logs: {logs}")
84
+
85
+ return logs
86
+
87
+ except docker.errors.DockerException as e:
88
+ print(
89
+ "Could not run the script in a container. If you haven't already, please install Docker https://docs.docker.com/get-docker/"
90
+ )
91
+ return f"Error: {str(e)}"
92
+
93
+ except Exception as e:
94
+ return f"Error: {str(e)}"
95
+
96
+
97
+ def execute_shell(command_line: str) -> str:
98
+ """Execute a shell command and return the output
99
+
100
+ Args:
101
+ command_line (str): The command line to execute
102
+
103
+ Returns:
104
+ str: The output of the command
105
+ """
106
+ current_dir = os.getcwd()
107
+ # Change dir into workspace if necessary
108
+ if str(WORKSPACE_PATH) not in current_dir:
109
+ os.chdir(WORKSPACE_PATH)
110
+
111
+ print(f"Executing command '{command_line}' in working directory '{os.getcwd()}'")
112
+
113
+ result = subprocess.run(command_line, capture_output=True, shell=True)
114
+ output = f"STDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}"
115
+
116
+ # Change back to whatever the prior working dir was
117
+
118
+ os.chdir(current_dir)
119
+
120
+ return output
121
+
122
+
123
+ def execute_shell_popen(command_line) -> str:
124
+ """Execute a shell command with Popen and returns an english description
125
+ of the event and the process id
126
+
127
+ Args:
128
+ command_line (str): The command line to execute
129
+
130
+ Returns:
131
+ str: Description of the fact that the process started and its id
132
+ """
133
+ current_dir = os.getcwd()
134
+ # Change dir into workspace if necessary
135
+ if str(WORKSPACE_PATH) not in current_dir:
136
+ os.chdir(WORKSPACE_PATH)
137
+
138
+ print(f"Executing command '{command_line}' in working directory '{os.getcwd()}'")
139
+
140
+ do_not_show_output = subprocess.DEVNULL
141
+ process = subprocess.Popen(
142
+ command_line, shell=True, stdout=do_not_show_output, stderr=do_not_show_output
143
+ )
144
+
145
+ # Change back to whatever the prior working dir was
146
+
147
+ os.chdir(current_dir)
148
+
149
+ return f"Subprocess started with PID:'{str(process.pid)}'"
150
+
151
+
152
+ def we_are_running_in_a_docker_container() -> bool:
153
+ """Check if we are running in a Docker container
154
+
155
+ Returns:
156
+ bool: True if we are running in a Docker container, False otherwise
157
+ """
158
+ return os.path.exists("/.dockerenv")
autogpt/commands/file_operations.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """File operations for AutoGPT"""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import os.path
6
+ from typing import Generator
7
+
8
+ import requests
9
+ from colorama import Back, Fore
10
+ from requests.adapters import HTTPAdapter, Retry
11
+
12
+ from autogpt.spinner import Spinner
13
+ from autogpt.utils import readable_file_size
14
+ from autogpt.workspace import WORKSPACE_PATH, path_in_workspace
15
+
16
+ LOG_FILE = "file_logger.txt"
17
+ LOG_FILE_PATH = WORKSPACE_PATH / LOG_FILE
18
+
19
+
20
+ def check_duplicate_operation(operation: str, filename: str) -> bool:
21
+ """Check if the operation has already been performed on the given file
22
+
23
+ Args:
24
+ operation (str): The operation to check for
25
+ filename (str): The name of the file to check for
26
+
27
+ Returns:
28
+ bool: True if the operation has already been performed on the file
29
+ """
30
+ log_content = read_file(LOG_FILE)
31
+ log_entry = f"{operation}: {filename}\n"
32
+ return log_entry in log_content
33
+
34
+
35
+ def log_operation(operation: str, filename: str) -> None:
36
+ """Log the file operation to the file_logger.txt
37
+
38
+ Args:
39
+ operation (str): The operation to log
40
+ filename (str): The name of the file the operation was performed on
41
+ """
42
+ log_entry = f"{operation}: {filename}\n"
43
+
44
+ # Create the log file if it doesn't exist
45
+ if not os.path.exists(LOG_FILE_PATH):
46
+ with open(LOG_FILE_PATH, "w", encoding="utf-8") as f:
47
+ f.write("File Operation Logger ")
48
+
49
+ append_to_file(LOG_FILE, log_entry, shouldLog=False)
50
+
51
+
52
+ def split_file(
53
+ content: str, max_length: int = 4000, overlap: int = 0
54
+ ) -> Generator[str, None, None]:
55
+ """
56
+ Split text into chunks of a specified maximum length with a specified overlap
57
+ between chunks.
58
+
59
+ :param content: The input text to be split into chunks
60
+ :param max_length: The maximum length of each chunk,
61
+ default is 4000 (about 1k token)
62
+ :param overlap: The number of overlapping characters between chunks,
63
+ default is no overlap
64
+ :return: A generator yielding chunks of text
65
+ """
66
+ start = 0
67
+ content_length = len(content)
68
+
69
+ while start < content_length:
70
+ end = start + max_length
71
+ if end + overlap < content_length:
72
+ chunk = content[start : end + overlap - 1]
73
+ else:
74
+ chunk = content[start:content_length]
75
+
76
+ # Account for the case where the last chunk is shorter than the overlap, so it has already been consumed
77
+ if len(chunk) <= overlap:
78
+ break
79
+
80
+ yield chunk
81
+ start += max_length - overlap
82
+
83
+
84
+ def read_file(filename: str) -> str:
85
+ """Read a file and return the contents
86
+
87
+ Args:
88
+ filename (str): The name of the file to read
89
+
90
+ Returns:
91
+ str: The contents of the file
92
+ """
93
+ try:
94
+ filepath = path_in_workspace(filename)
95
+ with open(filepath, "r", encoding="utf-8") as f:
96
+ content = f.read()
97
+ return content
98
+ except Exception as e:
99
+ return f"Error: {str(e)}"
100
+
101
+
102
+ def ingest_file(
103
+ filename: str, memory, max_length: int = 4000, overlap: int = 200
104
+ ) -> None:
105
+ """
106
+ Ingest a file by reading its content, splitting it into chunks with a specified
107
+ maximum length and overlap, and adding the chunks to the memory storage.
108
+
109
+ :param filename: The name of the file to ingest
110
+ :param memory: An object with an add() method to store the chunks in memory
111
+ :param max_length: The maximum length of each chunk, default is 4000
112
+ :param overlap: The number of overlapping characters between chunks, default is 200
113
+ """
114
+ try:
115
+ print(f"Working with file {filename}")
116
+ content = read_file(filename)
117
+ content_length = len(content)
118
+ print(f"File length: {content_length} characters")
119
+
120
+ chunks = list(split_file(content, max_length=max_length, overlap=overlap))
121
+
122
+ num_chunks = len(chunks)
123
+ for i, chunk in enumerate(chunks):
124
+ print(f"Ingesting chunk {i + 1} / {num_chunks} into memory")
125
+ memory_to_add = (
126
+ f"Filename: {filename}\n" f"Content part#{i + 1}/{num_chunks}: {chunk}"
127
+ )
128
+
129
+ memory.add(memory_to_add)
130
+
131
+ print(f"Done ingesting {num_chunks} chunks from {filename}.")
132
+ except Exception as e:
133
+ print(f"Error while ingesting file '{filename}': {str(e)}")
134
+
135
+
136
+ def write_to_file(filename: str, text: str) -> str:
137
+ """Write text to a file
138
+
139
+ Args:
140
+ filename (str): The name of the file to write to
141
+ text (str): The text to write to the file
142
+
143
+ Returns:
144
+ str: A message indicating success or failure
145
+ """
146
+ if check_duplicate_operation("write", filename):
147
+ return "Error: File has already been updated."
148
+ try:
149
+ filepath = path_in_workspace(filename)
150
+ directory = os.path.dirname(filepath)
151
+ if not os.path.exists(directory):
152
+ os.makedirs(directory)
153
+ with open(filepath, "w", encoding="utf-8") as f:
154
+ f.write(text)
155
+ log_operation("write", filename)
156
+ return "File written to successfully."
157
+ except Exception as e:
158
+ return f"Error: {str(e)}"
159
+
160
+
161
+ def append_to_file(filename: str, text: str, shouldLog: bool = True) -> str:
162
+ """Append text to a file
163
+
164
+ Args:
165
+ filename (str): The name of the file to append to
166
+ text (str): The text to append to the file
167
+
168
+ Returns:
169
+ str: A message indicating success or failure
170
+ """
171
+ try:
172
+ filepath = path_in_workspace(filename)
173
+ with open(filepath, "a") as f:
174
+ f.write(text)
175
+
176
+ if shouldLog:
177
+ log_operation("append", filename)
178
+
179
+ return "Text appended successfully."
180
+ except Exception as e:
181
+ return f"Error: {str(e)}"
182
+
183
+
184
+ def delete_file(filename: str) -> str:
185
+ """Delete a file
186
+
187
+ Args:
188
+ filename (str): The name of the file to delete
189
+
190
+ Returns:
191
+ str: A message indicating success or failure
192
+ """
193
+ if check_duplicate_operation("delete", filename):
194
+ return "Error: File has already been deleted."
195
+ try:
196
+ filepath = path_in_workspace(filename)
197
+ os.remove(filepath)
198
+ log_operation("delete", filename)
199
+ return "File deleted successfully."
200
+ except Exception as e:
201
+ return f"Error: {str(e)}"
202
+
203
+
204
+ def search_files(directory: str) -> list[str]:
205
+ """Search for files in a directory
206
+
207
+ Args:
208
+ directory (str): The directory to search in
209
+
210
+ Returns:
211
+ list[str]: A list of files found in the directory
212
+ """
213
+ found_files = []
214
+
215
+ if directory in {"", "/"}:
216
+ search_directory = WORKSPACE_PATH
217
+ else:
218
+ search_directory = path_in_workspace(directory)
219
+
220
+ for root, _, files in os.walk(search_directory):
221
+ for file in files:
222
+ if file.startswith("."):
223
+ continue
224
+ relative_path = os.path.relpath(os.path.join(root, file), WORKSPACE_PATH)
225
+ found_files.append(relative_path)
226
+
227
+ return found_files
228
+
229
+
230
+ def download_file(url, filename):
231
+ """Downloads a file
232
+ Args:
233
+ url (str): URL of the file to download
234
+ filename (str): Filename to save the file as
235
+ """
236
+ safe_filename = path_in_workspace(filename)
237
+ try:
238
+ message = f"{Fore.YELLOW}Downloading file from {Back.LIGHTBLUE_EX}{url}{Back.RESET}{Fore.RESET}"
239
+ with Spinner(message) as spinner:
240
+ session = requests.Session()
241
+ retry = Retry(total=3, backoff_factor=1, status_forcelist=[502, 503, 504])
242
+ adapter = HTTPAdapter(max_retries=retry)
243
+ session.mount("http://", adapter)
244
+ session.mount("https://", adapter)
245
+
246
+ total_size = 0
247
+ downloaded_size = 0
248
+
249
+ with session.get(url, allow_redirects=True, stream=True) as r:
250
+ r.raise_for_status()
251
+ total_size = int(r.headers.get("Content-Length", 0))
252
+ downloaded_size = 0
253
+
254
+ with open(safe_filename, "wb") as f:
255
+ for chunk in r.iter_content(chunk_size=8192):
256
+ f.write(chunk)
257
+ downloaded_size += len(chunk)
258
+
259
+ # Update the progress message
260
+ progress = f"{readable_file_size(downloaded_size)} / {readable_file_size(total_size)}"
261
+ spinner.update_message(f"{message} {progress}")
262
+
263
+ return f'Successfully downloaded and locally stored file: "{filename}"! (Size: {readable_file_size(total_size)})'
264
+ except requests.HTTPError as e:
265
+ return f"Got an HTTP Error whilst trying to download file: {e}"
266
+ except Exception as e:
267
+ return "Error: " + str(e)
autogpt/commands/git_operations.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Git operations for autogpt"""
2
+ import git
3
+
4
+ from autogpt.config import Config
5
+ from autogpt.workspace import path_in_workspace
6
+
7
+ CFG = Config()
8
+
9
+
10
+ def clone_repository(repo_url: str, clone_path: str) -> str:
11
+ """Clone a GitHub repository locally
12
+
13
+ Args:
14
+ repo_url (str): The URL of the repository to clone
15
+ clone_path (str): The path to clone the repository to
16
+
17
+ Returns:
18
+ str: The result of the clone operation"""
19
+ split_url = repo_url.split("//")
20
+ auth_repo_url = f"//{CFG.github_username}:{CFG.github_api_key}@".join(split_url)
21
+ safe_clone_path = path_in_workspace(clone_path)
22
+ try:
23
+ git.Repo.clone_from(auth_repo_url, safe_clone_path)
24
+ return f"""Cloned {repo_url} to {safe_clone_path}"""
25
+ except Exception as e:
26
+ return f"Error: {str(e)}"
autogpt/commands/google_search.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Google search command for Autogpt."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+
6
+ from duckduckgo_search import ddg
7
+
8
+ from autogpt.config import Config
9
+
10
+ CFG = Config()
11
+
12
+
13
+ def google_search(query: str, num_results: int = 8) -> str:
14
+ """Return the results of a Google search
15
+
16
+ Args:
17
+ query (str): The search query.
18
+ num_results (int): The number of results to return.
19
+
20
+ Returns:
21
+ str: The results of the search.
22
+ """
23
+ search_results = []
24
+ if not query:
25
+ return json.dumps(search_results)
26
+
27
+ results = ddg(query, max_results=num_results)
28
+ if not results:
29
+ return json.dumps(search_results)
30
+
31
+ for j in results:
32
+ search_results.append(j)
33
+
34
+ return json.dumps(search_results, ensure_ascii=False, indent=4)
35
+
36
+
37
+ def google_official_search(query: str, num_results: int = 8) -> str | list[str]:
38
+ """Return the results of a Google search using the official Google API
39
+
40
+ Args:
41
+ query (str): The search query.
42
+ num_results (int): The number of results to return.
43
+
44
+ Returns:
45
+ str: The results of the search.
46
+ """
47
+
48
+ from googleapiclient.discovery import build
49
+ from googleapiclient.errors import HttpError
50
+
51
+ try:
52
+ # Get the Google API key and Custom Search Engine ID from the config file
53
+ api_key = CFG.google_api_key
54
+ custom_search_engine_id = CFG.custom_search_engine_id
55
+
56
+ # Initialize the Custom Search API service
57
+ service = build("customsearch", "v1", developerKey=api_key)
58
+
59
+ # Send the search query and retrieve the results
60
+ result = (
61
+ service.cse()
62
+ .list(q=query, cx=custom_search_engine_id, num=num_results)
63
+ .execute()
64
+ )
65
+
66
+ # Extract the search result items from the response
67
+ search_results = result.get("items", [])
68
+
69
+ # Create a list of only the URLs from the search results
70
+ search_results_links = [item["link"] for item in search_results]
71
+
72
+ except HttpError as e:
73
+ # Handle errors in the API call
74
+ error_details = json.loads(e.content.decode())
75
+
76
+ # Check if the error is related to an invalid or missing API key
77
+ if error_details.get("error", {}).get(
78
+ "code"
79
+ ) == 403 and "invalid API key" in error_details.get("error", {}).get(
80
+ "message", ""
81
+ ):
82
+ return "Error: The provided Google API key is invalid or missing."
83
+ else:
84
+ return f"Error: {e}"
85
+
86
+ # Return the list of search result URLs
87
+ return search_results_links
autogpt/commands/image_gen.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
11
+ from autogpt.config import Config
12
+ from autogpt.workspace import path_in_workspace
13
+
14
+ CFG = Config()
15
+
16
+
17
+ def generate_image(prompt: str, size: int = 256) -> str:
18
+ """Generate an image from a prompt.
19
+
20
+ Args:
21
+ prompt (str): The prompt to use
22
+ size (int, optional): The size of the image. Defaults to 256. (Not supported by HuggingFace)
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, size)
32
+ # HuggingFace
33
+ elif CFG.image_provider == "huggingface":
34
+ return generate_image_with_hf(prompt, filename)
35
+ # SD WebUI
36
+ elif CFG.image_provider == "sdwebui":
37
+ return generate_image_with_sd_webui(prompt, filename, size)
38
+ return "No Image Provider Set"
39
+
40
+
41
+ def generate_image_with_hf(prompt: str, filename: str) -> str:
42
+ """Generate an image with HuggingFace's API.
43
+
44
+ Args:
45
+ prompt (str): The prompt to use
46
+ filename (str): The filename to save the image to
47
+
48
+ Returns:
49
+ str: The filename of the image
50
+ """
51
+ API_URL = (
52
+ f"https://api-inference.huggingface.co/models/{CFG.huggingface_image_model}"
53
+ )
54
+ if CFG.huggingface_api_token is None:
55
+ raise ValueError(
56
+ "You need to set your Hugging Face API token in the config file."
57
+ )
58
+ headers = {
59
+ "Authorization": f"Bearer {CFG.huggingface_api_token}",
60
+ "X-Use-Cache": "false",
61
+ }
62
+
63
+ response = requests.post(
64
+ API_URL,
65
+ headers=headers,
66
+ json={
67
+ "inputs": prompt,
68
+ },
69
+ )
70
+
71
+ image = Image.open(io.BytesIO(response.content))
72
+ print(f"Image Generated for prompt:{prompt}")
73
+
74
+ image.save(path_in_workspace(filename))
75
+
76
+ return f"Saved to disk:{filename}"
77
+
78
+
79
+ def generate_image_with_dalle(prompt: str, filename: str) -> str:
80
+ """Generate an image with DALL-E.
81
+
82
+ Args:
83
+ prompt (str): The prompt to use
84
+ filename (str): The filename to save the image to
85
+
86
+ Returns:
87
+ str: The filename of the image
88
+ """
89
+ openai.api_key = CFG.openai_api_key
90
+
91
+ # Check for supported image sizes
92
+ if size not in [256, 512, 1024]:
93
+ closest = min([256, 512, 1024], key=lambda x: abs(x - size))
94
+ print(
95
+ f"DALL-E only supports image sizes of 256x256, 512x512, or 1024x1024. Setting to {closest}, was {size}."
96
+ )
97
+ size = closest
98
+
99
+ response = openai.Image.create(
100
+ prompt=prompt,
101
+ n=1,
102
+ size=f"{size}x{size}",
103
+ response_format="b64_json",
104
+ )
105
+
106
+ print(f"Image Generated for prompt:{prompt}")
107
+
108
+ image_data = b64decode(response["data"][0]["b64_json"])
109
+
110
+ with open(path_in_workspace(filename), mode="wb") as png:
111
+ png.write(image_data)
112
+
113
+ return f"Saved to disk:{filename}"
114
+
115
+
116
+ def generate_image_with_sd_webui(
117
+ prompt: str,
118
+ filename: str,
119
+ size: int = 512,
120
+ negative_prompt: str = "",
121
+ extra: dict = {},
122
+ ) -> str:
123
+ """Generate an image with Stable Diffusion webui.
124
+ Args:
125
+ prompt (str): The prompt to use
126
+ filename (str): The filename to save the image to
127
+ size (int, optional): The size of the image. Defaults to 256.
128
+ negative_prompt (str, optional): The negative prompt to use. Defaults to "".
129
+ extra (dict, optional): Extra parameters to pass to the API. Defaults to {}.
130
+ Returns:
131
+ str: The filename of the image
132
+ """
133
+ # Create a session and set the basic auth if needed
134
+ s = requests.Session()
135
+ if CFG.sd_webui_auth:
136
+ username, password = CFG.sd_webui_auth.split(":")
137
+ s.auth = (username, password or "")
138
+
139
+ # Generate the images
140
+ response = requests.post(
141
+ f"{CFG.sd_webui_url}/sdapi/v1/txt2img",
142
+ json={
143
+ "prompt": prompt,
144
+ "negative_prompt": negative_prompt,
145
+ "sampler_index": "DDIM",
146
+ "steps": 20,
147
+ "cfg_scale": 7.0,
148
+ "width": size,
149
+ "height": size,
150
+ "n_iter": 1,
151
+ **extra,
152
+ },
153
+ )
154
+
155
+ print(f"Image Generated for prompt:{prompt}")
156
+
157
+ # Save the image to disk
158
+ response = response.json()
159
+ b64 = b64decode(response["images"][0].split(",", 1)[0])
160
+ image = Image.open(io.BytesIO(b64))
161
+ image.save(path_in_workspace(filename))
162
+
163
+ return f"Saved to disk:{filename}"
autogpt/commands/improve_code.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+
5
+ from autogpt.llm_utils import call_ai_function
6
+
7
+
8
+ def improve_code(suggestions: list[str], code: str) -> str:
9
+ """
10
+ A function that takes in code and suggestions and returns a response from create
11
+ chat completion api call.
12
+
13
+ Parameters:
14
+ suggestions (List): A list of suggestions around what needs to be improved.
15
+ code (str): Code to be improved.
16
+ Returns:
17
+ A result string from create chat completion. Improved code in response.
18
+ """
19
+
20
+ function_string = (
21
+ "def generate_improved_code(suggestions: List[str], code: str) -> str:"
22
+ )
23
+ args = [json.dumps(suggestions), code]
24
+ description_string = (
25
+ "Improves the provided code based on the suggestions"
26
+ " provided, making no other changes."
27
+ )
28
+
29
+ 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/twitter.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import tweepy
4
+ from dotenv import load_dotenv
5
+
6
+ load_dotenv()
7
+
8
+
9
+ def send_tweet(tweet_text):
10
+ consumer_key = os.environ.get("TW_CONSUMER_KEY")
11
+ consumer_secret = os.environ.get("TW_CONSUMER_SECRET")
12
+ access_token = os.environ.get("TW_ACCESS_TOKEN")
13
+ access_token_secret = os.environ.get("TW_ACCESS_TOKEN_SECRET")
14
+ # Authenticate to Twitter
15
+ auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
16
+ auth.set_access_token(access_token, access_token_secret)
17
+
18
+ # Create API object
19
+ api = tweepy.API(auth)
20
+
21
+ # Send tweet
22
+ try:
23
+ api.update_status(tweet_text)
24
+ print("Tweet sent successfully!")
25
+ except tweepy.TweepyException as e:
26
+ print("Error sending tweet: {}".format(e.reason))
autogpt/commands/web_playwright.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Web scraping commands using Playwright"""
2
+ from __future__ import annotations
3
+
4
+ try:
5
+ from playwright.sync_api import sync_playwright
6
+ except ImportError:
7
+ print(
8
+ "Playwright not installed. Please install it with 'pip install playwright' to use."
9
+ )
10
+ from bs4 import BeautifulSoup
11
+
12
+ from autogpt.processing.html import extract_hyperlinks, format_hyperlinks
13
+
14
+
15
+ def scrape_text(url: str) -> str:
16
+ """Scrape text from a webpage
17
+
18
+ Args:
19
+ url (str): The URL to scrape text from
20
+
21
+ Returns:
22
+ str: The scraped text
23
+ """
24
+ with sync_playwright() as p:
25
+ browser = p.chromium.launch()
26
+ page = browser.new_page()
27
+
28
+ try:
29
+ page.goto(url)
30
+ html_content = page.content()
31
+ soup = BeautifulSoup(html_content, "html.parser")
32
+
33
+ for script in soup(["script", "style"]):
34
+ script.extract()
35
+
36
+ text = soup.get_text()
37
+ lines = (line.strip() for line in text.splitlines())
38
+ chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
39
+ text = "\n".join(chunk for chunk in chunks if chunk)
40
+
41
+ except Exception as e:
42
+ text = f"Error: {str(e)}"
43
+
44
+ finally:
45
+ browser.close()
46
+
47
+ return text
48
+
49
+
50
+ def scrape_links(url: str) -> str | list[str]:
51
+ """Scrape links from a webpage
52
+
53
+ Args:
54
+ url (str): The URL to scrape links from
55
+
56
+ Returns:
57
+ Union[str, List[str]]: The scraped links
58
+ """
59
+ with sync_playwright() as p:
60
+ browser = p.chromium.launch()
61
+ page = browser.new_page()
62
+
63
+ try:
64
+ page.goto(url)
65
+ html_content = page.content()
66
+ soup = BeautifulSoup(html_content, "html.parser")
67
+
68
+ for script in soup(["script", "style"]):
69
+ script.extract()
70
+
71
+ hyperlinks = extract_hyperlinks(soup, url)
72
+ formatted_links = format_hyperlinks(hyperlinks)
73
+
74
+ except Exception as e:
75
+ formatted_links = f"Error: {str(e)}"
76
+
77
+ finally:
78
+ browser.close()
79
+
80
+ return formatted_links
autogpt/commands/web_requests.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Browse a webpage and summarize it using the LLM model"""
2
+ from __future__ import annotations
3
+
4
+ from urllib.parse import urljoin, urlparse
5
+
6
+ import requests
7
+ from bs4 import BeautifulSoup
8
+ from requests import Response
9
+ from requests.compat import urljoin
10
+
11
+ from autogpt.config import Config
12
+ from autogpt.memory import get_memory
13
+ from autogpt.processing.html import extract_hyperlinks, format_hyperlinks
14
+
15
+ CFG = Config()
16
+ memory = get_memory(CFG)
17
+
18
+ session = requests.Session()
19
+ session.headers.update({"User-Agent": CFG.user_agent})
20
+
21
+
22
+ def is_valid_url(url: str) -> bool:
23
+ """Check if the URL is valid
24
+
25
+ Args:
26
+ url (str): The URL to check
27
+
28
+ Returns:
29
+ bool: True if the URL is valid, False otherwise
30
+ """
31
+ try:
32
+ result = urlparse(url)
33
+ return all([result.scheme, result.netloc])
34
+ except ValueError:
35
+ return False
36
+
37
+
38
+ def sanitize_url(url: str) -> str:
39
+ """Sanitize the URL
40
+
41
+ Args:
42
+ url (str): The URL to sanitize
43
+
44
+ Returns:
45
+ str: The sanitized URL
46
+ """
47
+ return urljoin(url, urlparse(url).path)
48
+
49
+
50
+ def check_local_file_access(url: str) -> bool:
51
+ """Check if the URL is a local file
52
+
53
+ Args:
54
+ url (str): The URL to check
55
+
56
+ Returns:
57
+ bool: True if the URL is a local file, False otherwise
58
+ """
59
+ local_prefixes = [
60
+ "file:///",
61
+ "file://localhost/",
62
+ "file://localhost",
63
+ "http://localhost",
64
+ "http://localhost/",
65
+ "https://localhost",
66
+ "https://localhost/",
67
+ "http://2130706433",
68
+ "http://2130706433/",
69
+ "https://2130706433",
70
+ "https://2130706433/",
71
+ "http://127.0.0.1/",
72
+ "http://127.0.0.1",
73
+ "https://127.0.0.1/",
74
+ "https://127.0.0.1",
75
+ "https://0.0.0.0/",
76
+ "https://0.0.0.0",
77
+ "http://0.0.0.0/",
78
+ "http://0.0.0.0",
79
+ "http://0000",
80
+ "http://0000/",
81
+ "https://0000",
82
+ "https://0000/",
83
+ ]
84
+ return any(url.startswith(prefix) for prefix in local_prefixes)
85
+
86
+
87
+ def get_response(
88
+ url: str, timeout: int = 10
89
+ ) -> tuple[None, str] | tuple[Response, None]:
90
+ """Get the response from a URL
91
+
92
+ Args:
93
+ url (str): The URL to get the response from
94
+ timeout (int): The timeout for the HTTP request
95
+
96
+ Returns:
97
+ tuple[None, str] | tuple[Response, None]: The response and error message
98
+
99
+ Raises:
100
+ ValueError: If the URL is invalid
101
+ requests.exceptions.RequestException: If the HTTP request fails
102
+ """
103
+ try:
104
+ # Restrict access to local files
105
+ if check_local_file_access(url):
106
+ raise ValueError("Access to local files is restricted")
107
+
108
+ # Most basic check if the URL is valid:
109
+ if not url.startswith("http://") and not url.startswith("https://"):
110
+ raise ValueError("Invalid URL format")
111
+
112
+ sanitized_url = sanitize_url(url)
113
+
114
+ response = session.get(sanitized_url, timeout=timeout)
115
+
116
+ # Check if the response contains an HTTP error
117
+ if response.status_code >= 400:
118
+ return None, f"Error: HTTP {str(response.status_code)} error"
119
+
120
+ return response, None
121
+ except ValueError as ve:
122
+ # Handle invalid URL format
123
+ return None, f"Error: {str(ve)}"
124
+
125
+ except requests.exceptions.RequestException as re:
126
+ # Handle exceptions related to the HTTP request
127
+ # (e.g., connection errors, timeouts, etc.)
128
+ return None, f"Error: {str(re)}"
129
+
130
+
131
+ def scrape_text(url: str) -> str:
132
+ """Scrape text from a webpage
133
+
134
+ Args:
135
+ url (str): The URL to scrape text from
136
+
137
+ Returns:
138
+ str: The scraped text
139
+ """
140
+ response, error_message = get_response(url)
141
+ if error_message:
142
+ return error_message
143
+ if not response:
144
+ return "Error: Could not get response"
145
+
146
+ soup = BeautifulSoup(response.text, "html.parser")
147
+
148
+ for script in soup(["script", "style"]):
149
+ script.extract()
150
+
151
+ text = soup.get_text()
152
+ lines = (line.strip() for line in text.splitlines())
153
+ chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
154
+ text = "\n".join(chunk for chunk in chunks if chunk)
155
+
156
+ return text
157
+
158
+
159
+ def scrape_links(url: str) -> str | list[str]:
160
+ """Scrape links from a webpage
161
+
162
+ Args:
163
+ url (str): The URL to scrape links from
164
+
165
+ Returns:
166
+ str | list[str]: The scraped links
167
+ """
168
+ response, error_message = get_response(url)
169
+ if error_message:
170
+ return error_message
171
+ if not response:
172
+ return "Error: Could not get response"
173
+ soup = BeautifulSoup(response.text, "html.parser")
174
+
175
+ for script in soup(["script", "style"]):
176
+ script.extract()
177
+
178
+ hyperlinks = extract_hyperlinks(soup, url)
179
+
180
+ return format_hyperlinks(hyperlinks)
181
+
182
+
183
+ def create_message(chunk, question):
184
+ """Create a message for the user to summarize a chunk of text"""
185
+ return {
186
+ "role": "user",
187
+ "content": f'"""{chunk}""" Using the above text, answer the following'
188
+ f' question: "{question}" -- if the question cannot be answered using the'
189
+ " text, summarize the text.",
190
+ }
autogpt/commands/web_selenium.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Selenium web scraping module."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ from pathlib import Path
6
+ from sys import platform
7
+
8
+ from bs4 import BeautifulSoup
9
+ from selenium import webdriver
10
+ from selenium.webdriver.chrome.options import Options as ChromeOptions
11
+ from selenium.webdriver.common.by import By
12
+ from selenium.webdriver.firefox.options import Options as FirefoxOptions
13
+ from selenium.webdriver.remote.webdriver import WebDriver
14
+ from selenium.webdriver.safari.options import Options as SafariOptions
15
+ from selenium.webdriver.support import expected_conditions as EC
16
+ from selenium.webdriver.support.wait import WebDriverWait
17
+ from webdriver_manager.chrome import ChromeDriverManager
18
+ from webdriver_manager.firefox import GeckoDriverManager
19
+
20
+ import autogpt.processing.text as summary
21
+ from autogpt.config import Config
22
+ from autogpt.processing.html import extract_hyperlinks, format_hyperlinks
23
+
24
+ FILE_DIR = Path(__file__).parent.parent
25
+ CFG = Config()
26
+
27
+
28
+ def browse_website(url: str, question: str) -> tuple[str, WebDriver]:
29
+ """Browse a website and return the answer and links to the user
30
+
31
+ Args:
32
+ url (str): The url of the website to browse
33
+ question (str): The question asked by the user
34
+
35
+ Returns:
36
+ Tuple[str, WebDriver]: The answer and links to the user and the webdriver
37
+ """
38
+ driver, text = scrape_text_with_selenium(url)
39
+ add_header(driver)
40
+ summary_text = summary.summarize_text(url, text, question, driver)
41
+ links = scrape_links_with_selenium(driver, url)
42
+
43
+ # Limit links to 5
44
+ if len(links) > 5:
45
+ links = links[:5]
46
+ close_browser(driver)
47
+ return f"Answer gathered from website: {summary_text} \n \n Links: {links}", driver
48
+
49
+
50
+ def scrape_text_with_selenium(url: str) -> tuple[WebDriver, str]:
51
+ """Scrape text from a website using selenium
52
+
53
+ Args:
54
+ url (str): The url of the website to scrape
55
+
56
+ Returns:
57
+ Tuple[WebDriver, str]: The webdriver and the text scraped from the website
58
+ """
59
+ logging.getLogger("selenium").setLevel(logging.CRITICAL)
60
+
61
+ options_available = {
62
+ "chrome": ChromeOptions,
63
+ "safari": SafariOptions,
64
+ "firefox": FirefoxOptions,
65
+ }
66
+
67
+ options = options_available[CFG.selenium_web_browser]()
68
+ options.add_argument(
69
+ "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"
70
+ )
71
+
72
+ if CFG.selenium_web_browser == "firefox":
73
+ driver = webdriver.Firefox(
74
+ executable_path=GeckoDriverManager().install(), options=options
75
+ )
76
+ elif CFG.selenium_web_browser == "safari":
77
+ # Requires a bit more setup on the users end
78
+ # See https://developer.apple.com/documentation/webkit/testing_with_webdriver_in_safari
79
+ driver = webdriver.Safari(options=options)
80
+ else:
81
+ if platform == "linux" or platform == "linux2":
82
+ options.add_argument("--disable-dev-shm-usage")
83
+ options.add_argument("--remote-debugging-port=9222")
84
+
85
+ options.add_argument("--no-sandbox")
86
+ if CFG.selenium_headless:
87
+ options.add_argument("--headless")
88
+ options.add_argument("--disable-gpu")
89
+
90
+ driver = webdriver.Chrome(
91
+ executable_path=ChromeDriverManager().install(), options=options
92
+ )
93
+ driver.get(url)
94
+
95
+ WebDriverWait(driver, 10).until(
96
+ EC.presence_of_element_located((By.TAG_NAME, "body"))
97
+ )
98
+
99
+ # Get the HTML content directly from the browser's DOM
100
+ page_source = driver.execute_script("return document.body.outerHTML;")
101
+ soup = BeautifulSoup(page_source, "html.parser")
102
+
103
+ for script in soup(["script", "style"]):
104
+ script.extract()
105
+
106
+ text = soup.get_text()
107
+ lines = (line.strip() for line in text.splitlines())
108
+ chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
109
+ text = "\n".join(chunk for chunk in chunks if chunk)
110
+ return driver, text
111
+
112
+
113
+ def scrape_links_with_selenium(driver: WebDriver, url: str) -> list[str]:
114
+ """Scrape links from a website using selenium
115
+
116
+ Args:
117
+ driver (WebDriver): The webdriver to use to scrape the links
118
+
119
+ Returns:
120
+ List[str]: The links scraped from the website
121
+ """
122
+ page_source = driver.page_source
123
+ soup = BeautifulSoup(page_source, "html.parser")
124
+
125
+ for script in soup(["script", "style"]):
126
+ script.extract()
127
+
128
+ hyperlinks = extract_hyperlinks(soup, url)
129
+
130
+ return format_hyperlinks(hyperlinks)
131
+
132
+
133
+ def close_browser(driver: WebDriver) -> None:
134
+ """Close the browser
135
+
136
+ Args:
137
+ driver (WebDriver): The webdriver to close
138
+
139
+ Returns:
140
+ None
141
+ """
142
+ driver.quit()
143
+
144
+
145
+ def add_header(driver: WebDriver) -> None:
146
+ """Add a header to the website
147
+
148
+ Args:
149
+ driver (WebDriver): The webdriver to use to add the header
150
+
151
+ Returns:
152
+ None
153
+ """
154
+ driver.execute_script(open(f"{FILE_DIR}/js/overlay.js", "r").read())
autogpt/commands/write_tests.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A module that contains a function to generate test cases for the submitted code."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+
6
+ from autogpt.llm_utils import call_ai_function
7
+
8
+
9
+ def write_tests(code: str, focus: list[str]) -> str:
10
+ """
11
+ A function that takes in code and focus topics and returns a response from create
12
+ chat completion api call.
13
+
14
+ Parameters:
15
+ focus (list): A list of suggestions around what needs to be improved.
16
+ code (str): Code for test cases to be generated against.
17
+ Returns:
18
+ A result string from create chat completion. Test cases for the submitted code
19
+ in response.
20
+ """
21
+
22
+ function_string = (
23
+ "def create_test_cases(code: str, focus: Optional[str] = None) -> str:"
24
+ )
25
+ args = [code, json.dumps(focus)]
26
+ description_string = (
27
+ "Generates test cases for the existing code, focusing on"
28
+ " specific areas if required."
29
+ )
30
+
31
+ 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 Config, check_openai_api_key
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,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # sourcery skip: do-not-use-staticmethod
2
+ """
3
+ A module that contains the AIConfig class object that contains the configuration
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ from typing import Type
9
+
10
+ import yaml
11
+
12
+
13
+ class AIConfig:
14
+ """
15
+ A class object that contains the configuration information for the AI
16
+
17
+ Attributes:
18
+ ai_name (str): The name of the AI.
19
+ ai_role (str): The description of the AI's role.
20
+ ai_goals (list): The list of objectives the AI is supposed to complete.
21
+ """
22
+
23
+ def __init__(
24
+ self, ai_name: str = "", ai_role: str = "", ai_goals: list | None = None
25
+ ) -> None:
26
+ """
27
+ Initialize a class instance
28
+
29
+ Parameters:
30
+ ai_name (str): The name of the AI.
31
+ ai_role (str): The description of the AI's role.
32
+ ai_goals (list): The list of objectives the AI is supposed to complete.
33
+ Returns:
34
+ None
35
+ """
36
+ if ai_goals is None:
37
+ ai_goals = []
38
+ self.ai_name = ai_name
39
+ self.ai_role = ai_role
40
+ self.ai_goals = ai_goals
41
+
42
+ # Soon this will go in a folder where it remembers more stuff about the run(s)
43
+ SAVE_FILE = os.path.join(os.path.dirname(__file__), "..", "ai_settings.yaml")
44
+
45
+ @staticmethod
46
+ def load(config_file: str = SAVE_FILE) -> "AIConfig":
47
+ """
48
+ Returns class object with parameters (ai_name, ai_role, ai_goals) loaded from
49
+ yaml file if yaml file exists,
50
+ else returns class with no parameters.
51
+
52
+ Parameters:
53
+ config_file (int): The path to the config yaml file.
54
+ DEFAULT: "../ai_settings.yaml"
55
+
56
+ Returns:
57
+ cls (object): An instance of given cls object
58
+ """
59
+
60
+ try:
61
+ with open(config_file, encoding="utf-8") as file:
62
+ config_params = yaml.load(file, Loader=yaml.FullLoader)
63
+ except FileNotFoundError:
64
+ config_params = {}
65
+
66
+ ai_name = config_params.get("ai_name", "")
67
+ ai_role = config_params.get("ai_role", "")
68
+ ai_goals = config_params.get("ai_goals", [])
69
+ # type: Type[AIConfig]
70
+ return AIConfig(ai_name, ai_role, ai_goals)
71
+
72
+ def save(self, config_file: str = SAVE_FILE) -> None:
73
+ """
74
+ Saves the class parameters to the specified file yaml file path as a yaml file.
75
+
76
+ Parameters:
77
+ config_file(str): The path to the config yaml file.
78
+ DEFAULT: "../ai_settings.yaml"
79
+
80
+ Returns:
81
+ None
82
+ """
83
+
84
+ config = {
85
+ "ai_name": self.ai_name,
86
+ "ai_role": self.ai_role,
87
+ "ai_goals": self.ai_goals,
88
+ }
89
+ with open(config_file, "w", encoding="utf-8") as file:
90
+ yaml.dump(config, file, allow_unicode=True)
91
+
92
+ def construct_full_prompt(self) -> str:
93
+ """
94
+ Returns a prompt to the user with the class information in an organized fashion.
95
+
96
+ Parameters:
97
+ None
98
+
99
+ Returns:
100
+ full_prompt (str): A string containing the initial prompt for the user
101
+ including the ai_name, ai_role and ai_goals.
102
+ """
103
+
104
+ prompt_start = (
105
+ "Your decisions must always be made independently without"
106
+ " seeking user assistance. Play to your strengths as an LLM and pursue"
107
+ " simple strategies with no legal complications."
108
+ ""
109
+ )
110
+
111
+ from autogpt.prompt import get_prompt
112
+
113
+ # Construct full prompt
114
+ full_prompt = (
115
+ f"You are {self.ai_name}, {self.ai_role}\n{prompt_start}\n\nGOALS:\n\n"
116
+ )
117
+ for i, goal in enumerate(self.ai_goals):
118
+ full_prompt += f"{i+1}. {goal}\n"
119
+
120
+ full_prompt += f"\n\n{get_prompt()}"
121
+ return full_prompt
autogpt/config/config.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Configuration class to store the state of bools for different scripts access."""
2
+ import os
3
+
4
+ import openai
5
+ import yaml
6
+ from colorama import Fore
7
+ from dotenv import load_dotenv
8
+
9
+ from autogpt.config.singleton import Singleton
10
+
11
+ load_dotenv(verbose=True)
12
+
13
+
14
+ class Config(metaclass=Singleton):
15
+ """
16
+ Configuration class to store the state of bools for different scripts access.
17
+ """
18
+
19
+ def __init__(self) -> None:
20
+ """Initialize the Config class"""
21
+ self.debug_mode = False
22
+ self.continuous_mode = False
23
+ self.continuous_limit = 0
24
+ self.speak_mode = False
25
+ self.skip_reprompt = False
26
+ self.allow_downloads = False
27
+ self.skip_news = False
28
+
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
+
36
+ self.openai_api_key = os.getenv("OPENAI_API_KEY")
37
+ self.temperature = float(os.getenv("TEMPERATURE", "1"))
38
+ self.use_azure = os.getenv("USE_AZURE") == "True"
39
+ self.execute_local_commands = (
40
+ os.getenv("EXECUTE_LOCAL_COMMANDS", "False") == "True"
41
+ )
42
+ self.restrict_to_workspace = (
43
+ os.getenv("RESTRICT_TO_WORKSPACE", "True") == "True"
44
+ )
45
+
46
+ if self.use_azure:
47
+ self.load_azure_config()
48
+ openai.api_type = self.openai_api_type
49
+ openai.api_base = self.openai_api_base
50
+ openai.api_version = self.openai_api_version
51
+
52
+ self.elevenlabs_api_key = os.getenv("ELEVENLABS_API_KEY")
53
+ self.elevenlabs_voice_1_id = os.getenv("ELEVENLABS_VOICE_1_ID")
54
+ self.elevenlabs_voice_2_id = os.getenv("ELEVENLABS_VOICE_2_ID")
55
+
56
+ self.use_mac_os_tts = False
57
+ self.use_mac_os_tts = os.getenv("USE_MAC_OS_TTS")
58
+
59
+ self.use_brian_tts = False
60
+ self.use_brian_tts = os.getenv("USE_BRIAN_TTS")
61
+
62
+ self.github_api_key = os.getenv("GITHUB_API_KEY")
63
+ self.github_username = os.getenv("GITHUB_USERNAME")
64
+
65
+ self.google_api_key = os.getenv("GOOGLE_API_KEY")
66
+ self.custom_search_engine_id = os.getenv("CUSTOM_SEARCH_ENGINE_ID")
67
+
68
+ self.pinecone_api_key = os.getenv("PINECONE_API_KEY")
69
+ self.pinecone_region = os.getenv("PINECONE_ENV")
70
+
71
+ self.weaviate_host = os.getenv("WEAVIATE_HOST")
72
+ self.weaviate_port = os.getenv("WEAVIATE_PORT")
73
+ self.weaviate_protocol = os.getenv("WEAVIATE_PROTOCOL", "http")
74
+ self.weaviate_username = os.getenv("WEAVIATE_USERNAME", None)
75
+ self.weaviate_password = os.getenv("WEAVIATE_PASSWORD", None)
76
+ self.weaviate_scopes = os.getenv("WEAVIATE_SCOPES", None)
77
+ self.weaviate_embedded_path = os.getenv("WEAVIATE_EMBEDDED_PATH")
78
+ self.weaviate_api_key = os.getenv("WEAVIATE_API_KEY", None)
79
+ self.use_weaviate_embedded = (
80
+ os.getenv("USE_WEAVIATE_EMBEDDED", "False") == "True"
81
+ )
82
+
83
+ # milvus configuration, e.g., localhost:19530.
84
+ self.milvus_addr = os.getenv("MILVUS_ADDR", "localhost:19530")
85
+ self.milvus_collection = os.getenv("MILVUS_COLLECTION", "autogpt")
86
+
87
+ self.image_provider = os.getenv("IMAGE_PROVIDER")
88
+ self.image_size = int(os.getenv("IMAGE_SIZE", 256))
89
+ self.huggingface_api_token = os.getenv("HUGGINGFACE_API_TOKEN")
90
+ self.huggingface_image_model = os.getenv(
91
+ "HUGGINGFACE_IMAGE_MODEL", "CompVis/stable-diffusion-v1-4"
92
+ )
93
+ self.huggingface_audio_to_text_model = os.getenv(
94
+ "HUGGINGFACE_AUDIO_TO_TEXT_MODEL"
95
+ )
96
+ self.sd_webui_url = os.getenv("SD_WEBUI_URL", "http://localhost:7860")
97
+ self.sd_webui_auth = os.getenv("SD_WEBUI_AUTH")
98
+
99
+ # Selenium browser settings
100
+ self.selenium_web_browser = os.getenv("USE_WEB_BROWSER", "chrome")
101
+ self.selenium_headless = os.getenv("HEADLESS_BROWSER", "True") == "True"
102
+
103
+ # User agent header to use when making HTTP requests
104
+ # Some websites might just completely deny request with an error code if
105
+ # no user agent was found.
106
+ self.user_agent = os.getenv(
107
+ "USER_AGENT",
108
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36"
109
+ " (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36",
110
+ )
111
+
112
+ self.redis_host = os.getenv("REDIS_HOST", "localhost")
113
+ self.redis_port = os.getenv("REDIS_PORT", "6379")
114
+ self.redis_password = os.getenv("REDIS_PASSWORD", "")
115
+ self.wipe_redis_on_start = os.getenv("WIPE_REDIS_ON_START", "True") == "True"
116
+ self.memory_index = os.getenv("MEMORY_INDEX", "auto-gpt")
117
+ # Note that indexes must be created on db 0 in redis, this is not configurable.
118
+
119
+ self.memory_backend = os.getenv("MEMORY_BACKEND", "local")
120
+ # Initialize the OpenAI API client
121
+ openai.api_key = self.openai_api_key
122
+
123
+ def get_azure_deployment_id_for_model(self, model: str) -> str:
124
+ """
125
+ Returns the relevant deployment id for the model specified.
126
+
127
+ Parameters:
128
+ model(str): The model to map to the deployment id.
129
+
130
+ Returns:
131
+ The matching deployment id if found, otherwise an empty string.
132
+ """
133
+ if model == self.fast_llm_model:
134
+ return self.azure_model_to_deployment_id_map[
135
+ "fast_llm_model_deployment_id"
136
+ ] # type: ignore
137
+ elif model == self.smart_llm_model:
138
+ return self.azure_model_to_deployment_id_map[
139
+ "smart_llm_model_deployment_id"
140
+ ] # type: ignore
141
+ elif model == "text-embedding-ada-002":
142
+ return self.azure_model_to_deployment_id_map[
143
+ "embedding_model_deployment_id"
144
+ ] # type: ignore
145
+ else:
146
+ return ""
147
+
148
+ AZURE_CONFIG_FILE = os.path.join(os.path.dirname(__file__), "..", "azure.yaml")
149
+
150
+ def load_azure_config(self, config_file: str = AZURE_CONFIG_FILE) -> None:
151
+ """
152
+ Loads the configuration parameters for Azure hosting from the specified file
153
+ path as a yaml file.
154
+
155
+ Parameters:
156
+ config_file(str): The path to the config yaml file. DEFAULT: "../azure.yaml"
157
+
158
+ Returns:
159
+ None
160
+ """
161
+ try:
162
+ with open(config_file) as file:
163
+ config_params = yaml.load(file, Loader=yaml.FullLoader)
164
+ except FileNotFoundError:
165
+ config_params = {}
166
+ self.openai_api_type = config_params.get("azure_api_type") or "azure"
167
+ self.openai_api_base = config_params.get("azure_api_base") or ""
168
+ self.openai_api_version = (
169
+ config_params.get("azure_api_version") or "2023-03-15-preview"
170
+ )
171
+ self.azure_model_to_deployment_id_map = config_params.get("azure_model_map", [])
172
+
173
+ def set_continuous_mode(self, value: bool) -> None:
174
+ """Set the continuous mode value."""
175
+ self.continuous_mode = value
176
+
177
+ def set_continuous_limit(self, value: int) -> None:
178
+ """Set the continuous limit value."""
179
+ self.continuous_limit = value
180
+
181
+ def set_speak_mode(self, value: bool) -> None:
182
+ """Set the speak mode value."""
183
+ self.speak_mode = value
184
+
185
+ def set_fast_llm_model(self, value: str) -> None:
186
+ """Set the fast LLM model value."""
187
+ self.fast_llm_model = value
188
+
189
+ def set_smart_llm_model(self, value: str) -> None:
190
+ """Set the smart LLM model value."""
191
+ self.smart_llm_model = value
192
+
193
+ def set_fast_token_limit(self, value: int) -> None:
194
+ """Set the fast token limit value."""
195
+ self.fast_token_limit = value
196
+
197
+ def set_smart_token_limit(self, value: int) -> None:
198
+ """Set the smart token limit value."""
199
+ self.smart_token_limit = value
200
+
201
+ def set_browse_chunk_max_length(self, value: int) -> None:
202
+ """Set the browse_website command chunk max length value."""
203
+ self.browse_chunk_max_length = value
204
+
205
+ def set_openai_api_key(self, value: str) -> None:
206
+ """Set the OpenAI API key value."""
207
+ self.openai_api_key = value
208
+
209
+ def set_elevenlabs_api_key(self, value: str) -> None:
210
+ """Set the ElevenLabs API key value."""
211
+ self.elevenlabs_api_key = value
212
+
213
+ def set_elevenlabs_voice_1_id(self, value: str) -> None:
214
+ """Set the ElevenLabs Voice 1 ID value."""
215
+ self.elevenlabs_voice_1_id = value
216
+
217
+ def set_elevenlabs_voice_2_id(self, value: str) -> None:
218
+ """Set the ElevenLabs Voice 2 ID value."""
219
+ self.elevenlabs_voice_2_id = value
220
+
221
+ def set_google_api_key(self, value: str) -> None:
222
+ """Set the Google API key value."""
223
+ self.google_api_key = value
224
+
225
+ def set_custom_search_engine_id(self, value: str) -> None:
226
+ """Set the custom search engine id value."""
227
+ self.custom_search_engine_id = value
228
+
229
+ def set_pinecone_api_key(self, value: str) -> None:
230
+ """Set the Pinecone API key value."""
231
+ self.pinecone_api_key = value
232
+
233
+ def set_pinecone_region(self, value: str) -> None:
234
+ """Set the Pinecone region value."""
235
+ self.pinecone_region = value
236
+
237
+ def set_debug_mode(self, value: bool) -> None:
238
+ """Set the debug mode value."""
239
+ self.debug_mode = value
240
+
241
+
242
+ def check_openai_api_key() -> None:
243
+ """Check if the OpenAI API key is set in config.py or as an environment variable."""
244
+ cfg = Config()
245
+ if not cfg.openai_api_key:
246
+ print(
247
+ Fore.RED
248
+ + "Please set your OpenAI API key in .env or as an environment variable."
249
+ )
250
+ print("You can get your key from https://platform.openai.com/account/api-keys")
251
+ exit(1)