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