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