├── .devcontainer ├── Dockerfile └── devcontainer.json ├── .env.template ├── .flake8 ├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── 1.bug.yml │ └── 2.feature.yml ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── auto_format.yml │ ├── ci.yml │ ├── docker-image.yml │ └── dockerhub-imagepush.yml ├── .gitignore ├── .isort.cfg ├── .pre-commit-config.yaml ├── .sourcery.yaml ├── AutoGpt.json ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE ├── README.md ├── autogpt ├── __init__.py ├── __main__.py ├── agent │ ├── __init__.py │ ├── agent.py │ └── agent_manager.py ├── agent_manager.py ├── app.py ├── args.py ├── browse.py ├── chat.py ├── commands │ ├── __init__.py │ ├── audio_text.py │ ├── evaluate_code.py │ ├── execute_code.py │ ├── file_operations.py │ ├── git_operations.py │ ├── google_search.py │ ├── image_gen.py │ ├── improve_code.py │ ├── times.py │ ├── twitter.py │ ├── web_playwright.py │ ├── web_requests.py │ ├── web_selenium.py │ └── write_tests.py ├── config │ ├── __init__.py │ ├── ai_config.py │ ├── config.py │ └── singleton.py ├── data_ingestion.py ├── file_operations.py ├── image_gen.py ├── js │ └── overlay.js ├── json_fixes │ ├── __init__.py │ ├── auto_fix.py │ ├── bracket_termination.py │ ├── escaping.py │ ├── missing_quotes.py │ ├── parsing.py │ └── utilities.py ├── json_parser.py ├── json_utils.py ├── llm_utils.py ├── logs.py ├── memory │ ├── __init__.py │ ├── base.py │ ├── local.py │ ├── milvus.py │ ├── no_memory.py │ ├── pinecone.py │ ├── redismem.py │ └── weaviate.py ├── permanent_memory │ ├── __init__.py │ └── sqlite3_store.py ├── processing │ ├── __init__.py │ ├── html.py │ └── text.py ├── prompt.py ├── promptgenerator.py ├── setup.py ├── speak.py ├── speech │ ├── __init__.py │ ├── base.py │ ├── brian.py │ ├── eleven_labs.py │ ├── gtts.py │ ├── macos_tts.py │ └── say.py ├── spinner.py ├── summary.py ├── token_counter.py ├── utils.py ├── web.py └── workspace.py ├── azure.yaml.template ├── docker-compose.yml ├── docs └── imgs │ ├── demo.gif │ ├── gzh.png │ └── openai-api-key-billing-paid-account.png ├── main.py ├── openai-api-key.png ├── outputs ├── guest_post_email.txt ├── how_to_save_money_on_energy_bills.txt ├── logs │ ├── message-log-1.txt │ ├── message-log-2.txt │ ├── message-log-3.txt │ └── message-log-4.txt ├── post1_output.txt └── post2_output.txt ├── pyproject.toml ├── requirements-docker.txt ├── requirements.txt ├── run.bat ├── run_continuous.bat ├── scripts ├── check_requirements.py ├── execute_code.py ├── file_operations.py ├── main.py └── prompt.py ├── tests.py └── tests ├── __init__.py ├── browse_tests.py ├── context.py ├── integration ├── memory_tests.py ├── milvus_memory_tests.py └── weaviate_memory_tests.py ├── local_cache_test.py ├── milvus_memory_test.py ├── smoke_test.py ├── test_config.py ├── test_json_parser.py ├── test_prompt_generator.py ├── test_token_counter.py └── unit ├── json_tests.py ├── test_browse_scrape_links.py ├── test_browse_scrape_text.py ├── test_chat.py └── test_commands.py /.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | # [Choice] Python version (use -bullseye variants on local arm64/Apple Silicon): 3, 3.10, 3.9, 3.8, 3.7, 3.6, 3-bullseye, 3.10-bullseye, 3.9-bullseye, 3.8-bullseye, 3.7-bullseye, 3.6-bullseye, 3-buster, 3.10-buster, 3.9-buster, 3.8-buster, 3.7-buster, 3.6-buster 2 | ARG VARIANT=3-bullseye 3 | FROM python:3.8 4 | 5 | RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ 6 | # Remove imagemagick due to https://security-tracker.debian.org/tracker/CVE-2019-10131 7 | && apt-get purge -y imagemagick imagemagick-6-common 8 | 9 | # Temporary: Upgrade python packages due to https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-40897 10 | # They are installed by the base image (python) which does not have the patch. 11 | RUN python3 -m pip install --upgrade setuptools 12 | 13 | # [Optional] If your pip requirements rarely change, uncomment this section to add them to the image. 14 | # COPY requirements.txt /tmp/pip-tmp/ 15 | # RUN pip3 --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements.txt \ 16 | # && rm -rf /tmp/pip-tmp 17 | 18 | # [Optional] Uncomment this section to install additional OS packages. 19 | # RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ 20 | # && apt-get -y install --no-install-recommends 21 | 22 | # [Optional] Uncomment this line to install global node packages. 23 | # RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g " 2>&1 -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "build": { 3 | "dockerfile": "./Dockerfile", 4 | "context": "." 5 | }, 6 | "features": { 7 | "ghcr.io/devcontainers/features/common-utils:2": { 8 | "installZsh": "true", 9 | "username": "vscode", 10 | "userUid": "1000", 11 | "userGid": "1000", 12 | "upgradePackages": "true" 13 | }, 14 | "ghcr.io/devcontainers/features/python:1": "none", 15 | "ghcr.io/devcontainers/features/node:1": "none", 16 | "ghcr.io/devcontainers/features/git:1": { 17 | "version": "latest", 18 | "ppa": "false" 19 | } 20 | }, 21 | // Configure tool-specific properties. 22 | "customizations": { 23 | // Configure properties specific to VS Code. 24 | "vscode": { 25 | // Set *default* container specific settings.json values on container create. 26 | "settings": { 27 | "python.defaultInterpreterPath": "/usr/local/bin/python" 28 | } 29 | } 30 | }, 31 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 32 | // "forwardPorts": [], 33 | 34 | // Use 'postCreateCommand' to run commands after the container is created. 35 | // "postCreateCommand": "pip3 install --user -r requirements.txt", 36 | 37 | // Set `remoteUser` to `root` to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. 38 | "remoteUser": "vscode" 39 | } 40 | -------------------------------------------------------------------------------- /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-line-length = 88 3 | extend-ignore = E203 4 | exclude = 5 | .tox, 6 | __pycache__, 7 | *.pyc, 8 | .env 9 | venv/* 10 | .venv/* 11 | reports/* 12 | dist/* -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: Torantulino 4 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/1.bug.yml: -------------------------------------------------------------------------------- 1 | name: Bug report 🐛 2 | description: Create a bug report for Auto-GPT. 3 | labels: ['status: needs triage'] 4 | body: 5 | - type: checkboxes 6 | attributes: 7 | label: ⚠️ Search for existing issues first ⚠️ 8 | description: > 9 | Please [search the history](https://github.com/Torantulino/Auto-GPT/issues) 10 | to see if an issue already exists for the same problem. 11 | options: 12 | - label: I have searched the existing issues, and there is no existing issue for my problem 13 | required: true 14 | - type: markdown 15 | attributes: 16 | value: | 17 | Please provide a searchable summary of the issue in the title above ⬆️. 18 | 19 | ⚠️ SUPER-busy repo, please help the volunteer maintainers. 20 | The less time we spend here, the more time we spend building AutoGPT. 21 | 22 | Please help us help you: 23 | - Does it work on `stable` branch (https://github.com/Torantulino/Auto-GPT/tree/stable)? 24 | - Does it work on current `master` (https://github.com/Torantulino/Auto-GPT/tree/master)? 25 | - Search for existing issues, "add comment" is tidier than "new issue" 26 | - Ask on our Discord (https://discord.gg/autogpt) 27 | - Provide relevant info: 28 | - Provide commit-hash (`git rev-parse HEAD` gets it) 29 | - If it's a pip/packages issue, provide pip version, python version 30 | - If it's a crash, provide traceback. 31 | - type: checkboxes 32 | attributes: 33 | label: GPT-3 or GPT-4 34 | description: > 35 | If you are using Auto-GPT with `--gpt3only`, your problems may be caused by 36 | the limitations of GPT-3.5 37 | options: 38 | - label: I am using Auto-GPT with GPT-3 (GPT-3.5) 39 | - type: textarea 40 | attributes: 41 | label: Steps to reproduce 🕹 42 | description: | 43 | **⚠️ Issues that we can't reproduce will be closed.** 44 | - type: textarea 45 | attributes: 46 | label: Current behavior 😯 47 | description: Describe what happens instead of the expected behavior. 48 | - type: textarea 49 | attributes: 50 | label: Expected behavior 🤔 51 | description: Describe what should happen. 52 | - type: textarea 53 | attributes: 54 | label: Your prompt 📝 55 | description: | 56 | If applicable please provide the prompt you are using. You can find your last-used prompt in last_run_ai_settings.yaml. 57 | value: | 58 | ```yaml 59 | # Paste your prompt here 60 | ``` 61 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/2.feature.yml: -------------------------------------------------------------------------------- 1 | name: Feature request 🚀 2 | description: Suggest a new idea for Auto-GPT. 3 | labels: ['status: needs triage'] 4 | body: 5 | - type: markdown 6 | attributes: 7 | value: | 8 | Please provide a searchable summary of the issue in the title above ⬆️. 9 | 10 | Thanks for contributing by creating an issue! ❤️ 11 | - type: checkboxes 12 | attributes: 13 | label: Duplicates 14 | description: Please [search the history](https://github.com/Torantulino/Auto-GPT/issues) to see if an issue already exists for the same problem. 15 | options: 16 | - label: I have searched the existing issues 17 | required: true 18 | - type: textarea 19 | attributes: 20 | label: Summary 💡 21 | description: Describe how it should work. 22 | - type: textarea 23 | attributes: 24 | label: Examples 🌈 25 | description: Provide a link to other implementations, or screenshots of the expected behavior. 26 | - type: textarea 27 | attributes: 28 | label: Motivation 🔦 29 | description: What are you trying to accomplish? How has the lack of this feature affected you? Providing context helps us come up with a solution that is more useful in the real world. -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 11 | 12 | ### Background 13 | 14 | 15 | ### Changes 16 | 17 | 18 | ### Documentation 19 | 20 | 21 | ### Test Plan 22 | 23 | 24 | ### PR Quality Checklist 25 | - [ ] My pull request is atomic and focuses on a single change. 26 | - [ ] I have thoroughly tested my changes with multiple different prompts. 27 | - [ ] I have considered potential risks and mitigations for my changes. 28 | - [ ] I have documented my changes clearly and comprehensively. 29 | - [ ] I have not snuck in any "extra" small tweaks changes 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /.github/workflows/auto_format.yml: -------------------------------------------------------------------------------- 1 | name: auto-format 2 | on: pull_request 3 | jobs: 4 | format: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - name: Checkout PR branch 8 | uses: actions/checkout@v2 9 | with: 10 | ref: ${{ github.event.pull_request.head.sha }} 11 | - name: autopep8 12 | uses: peter-evans/autopep8@v1 13 | with: 14 | args: --exit-code --recursive --in-place --aggressive --aggressive . 15 | - name: Check for modified files 16 | id: git-check 17 | run: echo "modified=$(if git diff-index --quiet HEAD --; then echo "false"; else echo "true"; fi)" >> $GITHUB_ENV 18 | - name: Push changes 19 | if: steps.git-check.outputs.modified == 'true' 20 | run: | 21 | git config --global user.name 'Torantulino' 22 | git config --global user.email 'toran.richards@gmail.com' 23 | git remote set 24 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Python CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | branches: 9 | - master 10 | 11 | jobs: 12 | build: 13 | runs-on: ubuntu-latest 14 | 15 | strategy: 16 | matrix: 17 | python-version: [3.8] 18 | 19 | steps: 20 | - name: Check out repository 21 | uses: actions/checkout@v2 22 | 23 | - name: Set up Python ${{ matrix.python-version }} 24 | uses: actions/setup-python@v2 25 | with: 26 | python-version: ${{ matrix.python-version }} 27 | 28 | - name: Install dependencies 29 | run: | 30 | python -m pip install --upgrade pip 31 | pip install -r requirements.txt 32 | 33 | - name: Lint with flake8 34 | continue-on-error: false 35 | run: flake8 autogpt/ tests/ --select E303,W293,W291,W292,E305,E231,E302 36 | 37 | - name: Run unittest tests with coverage 38 | run: | 39 | coverage run --source=autogpt -m unittest discover tests 40 | 41 | - name: Generate coverage report 42 | run: | 43 | coverage report 44 | coverage xml 45 | -------------------------------------------------------------------------------- /.github/workflows/docker-image.yml: -------------------------------------------------------------------------------- 1 | name: Docker Image CI 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | pull_request: 7 | branches: [ "master" ] 8 | 9 | jobs: 10 | 11 | build: 12 | 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v3 17 | - name: Build the Docker image 18 | run: docker build . --file Dockerfile --tag autogpt:$(date +%s) 19 | -------------------------------------------------------------------------------- /.github/workflows/dockerhub-imagepush.yml: -------------------------------------------------------------------------------- 1 | name: Push Docker Image on Release 2 | 3 | on: 4 | push: 5 | branches: [ "stable" ] 6 | 7 | jobs: 8 | 9 | build: 10 | 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v3 15 | - name: Log in to Docker hub 16 | env: 17 | DOCKER_USER: ${{secrets.DOCKER_USER}} 18 | DOCKER_PASSWORD: ${{secrets.DOCKER_PASSWORD}} 19 | run: | 20 | docker login -u $DOCKER_USER -p $DOCKER_PASSWORD 21 | - name: Build the Docker image 22 | run: docker build . --file Dockerfile --tag ${{secrets.DOCKER_USER}}/auto-gpt:$(git describe --tags `git rev-list --tags --max-count=1`) 23 | - name: Docker Push 24 | run: docker push ${{secrets.DOCKER_USER}}/auto-gpt 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Original ignores 2 | autogpt/keys.py 3 | autogpt/*json 4 | autogpt/node_modules/ 5 | autogpt/__pycache__/keys.cpython-310.pyc 6 | package-lock.json 7 | *.pyc 8 | auto_gpt_workspace/* 9 | *.mpeg 10 | .env 11 | azure.yaml 12 | *venv/* 13 | outputs/* 14 | ai_settings.yaml 15 | last_run_ai_settings.yaml 16 | .vscode 17 | .idea/* 18 | auto-gpt.json 19 | log.txt 20 | log-ingestion.txt 21 | logs 22 | *.log 23 | *.mp3 24 | 25 | # Byte-compiled / optimized / DLL files 26 | __pycache__/ 27 | *.py[cod] 28 | *$py.class 29 | 30 | # C extensions 31 | *.so 32 | 33 | # Distribution / packaging 34 | .Python 35 | build/ 36 | develop-eggs/ 37 | dist/ 38 | plugins/ 39 | downloads/ 40 | eggs/ 41 | .eggs/ 42 | lib/ 43 | lib64/ 44 | parts/ 45 | sdist/ 46 | var/ 47 | wheels/ 48 | pip-wheel-metadata/ 49 | share/python-wheels/ 50 | *.egg-info/ 51 | .installed.cfg 52 | *.egg 53 | MANIFEST 54 | 55 | # PyInstaller 56 | # Usually these files are written by a python script from a template 57 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 58 | *.manifest 59 | *.spec 60 | 61 | # Installer logs 62 | pip-log.txt 63 | pip-delete-this-directory.txt 64 | 65 | # Unit test / coverage reports 66 | htmlcov/ 67 | .tox/ 68 | .nox/ 69 | .coverage 70 | .coverage.* 71 | .cache 72 | nosetests.xml 73 | coverage.xml 74 | *.cover 75 | *.py,cover 76 | .hypothesis/ 77 | .pytest_cache/ 78 | 79 | # Translations 80 | *.mo 81 | *.pot 82 | 83 | # Django stuff: 84 | *.log 85 | local_settings.py 86 | db.sqlite3 87 | db.sqlite3-journal 88 | 89 | # Flask stuff: 90 | instance/ 91 | .webassets-cache 92 | 93 | # Scrapy stuff: 94 | .scrapy 95 | 96 | # Sphinx documentation 97 | docs/_build/ 98 | 99 | # PyBuilder 100 | target/ 101 | 102 | # Jupyter Notebook 103 | .ipynb_checkpoints 104 | 105 | # IPython 106 | profile_default/ 107 | ipython_config.py 108 | 109 | # pyenv 110 | .python-version 111 | 112 | # pipenv 113 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 114 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 115 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 116 | # install all needed dependencies. 117 | #Pipfile.lock 118 | 119 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 120 | __pypackages__/ 121 | 122 | # Celery stuff 123 | celerybeat-schedule 124 | celerybeat.pid 125 | 126 | # SageMath parsed files 127 | *.sage.py 128 | 129 | # Environments 130 | .env 131 | .venv 132 | env/ 133 | venv/ 134 | ENV/ 135 | env.bak/ 136 | venv.bak/ 137 | 138 | # Spyder project settings 139 | .spyderproject 140 | .spyproject 141 | 142 | # Rope project settings 143 | .ropeproject 144 | 145 | # mkdocs documentation 146 | /site 147 | 148 | # mypy 149 | .mypy_cache/ 150 | .dmypy.json 151 | dmypy.json 152 | 153 | # Pyre type checker 154 | .pyre/ 155 | llama-* 156 | vicuna-* 157 | 158 | # mac 159 | .DS_Store 160 | -------------------------------------------------------------------------------- /.isort.cfg: -------------------------------------------------------------------------------- 1 | [settings] 2 | profile = black 3 | multi_line_output = 3 4 | include_trailing_comma = True 5 | force_grid_wrap = 0 6 | use_parentheses = True 7 | ensure_newline_before_comments = True 8 | line_length = 88 9 | skip = venv,env,node_modules,.env,.venv,dist 10 | sections = FUTURE,STDLIB,THIRDPARTY,FIRSTPARTY,LOCALFOLDER -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/sourcery-ai/sourcery 3 | rev: v1.1.0 # Get the latest tag from https://github.com/sourcery-ai/sourcery/tags 4 | hooks: 5 | - id: sourcery 6 | 7 | - repo: https://github.com/pre-commit/pre-commit-hooks 8 | rev: v0.9.2 9 | hooks: 10 | - id: check-added-large-files 11 | args: [ '--maxkb=500' ] 12 | - id: check-byte-order-marker 13 | - id: check-case-conflict 14 | - id: check-merge-conflict 15 | - id: check-symlinks 16 | - id: debug-statements 17 | 18 | - repo: local 19 | hooks: 20 | - id: isort 21 | name: isort-local 22 | entry: isort 23 | language: python 24 | types: [ python ] 25 | exclude: .+/(dist|.venv|venv|build)/.+ 26 | pass_filenames: true 27 | - id: black 28 | name: black-local 29 | entry: black 30 | language: python 31 | types: [ python ] 32 | exclude: .+/(dist|.venv|venv|build)/.+ 33 | pass_filenames: true -------------------------------------------------------------------------------- /.sourcery.yaml: -------------------------------------------------------------------------------- 1 | # 🪄 This is your project's Sourcery configuration file. 2 | 3 | # You can use it to get Sourcery working in the way you want, such as 4 | # ignoring specific refactorings, skipping directories in your project, 5 | # or writing custom rules. 6 | 7 | # 📚 For a complete reference to this file, see the documentation at 8 | # https://docs.sourcery.ai/Configuration/Project-Settings/ 9 | 10 | # This file was auto-generated by Sourcery on 2023-02-25 at 21:07. 11 | 12 | version: '1' # The schema version of this config file 13 | 14 | ignore: # A list of paths or files which Sourcery will ignore. 15 | - .git 16 | - venv 17 | - .venv 18 | - build 19 | - dist 20 | - env 21 | - .env 22 | - .tox 23 | 24 | rule_settings: 25 | enable: 26 | - default 27 | - gpsg 28 | disable: [] # A list of rule IDs Sourcery will never suggest. 29 | rule_types: 30 | - refactoring 31 | - suggestion 32 | - comment 33 | python_version: '3.9' # A string specifying the lowest Python version your project supports. Sourcery will not suggest refactorings requiring a higher Python version. 34 | 35 | # rules: # A list of custom rules Sourcery will include in its analysis. 36 | # - id: no-print-statements 37 | # description: Do not use print statements in the test directory. 38 | # pattern: print(...) 39 | # language: python 40 | # replacement: 41 | # condition: 42 | # explanation: 43 | # paths: 44 | # include: 45 | # - test 46 | # exclude: 47 | # - conftest.py 48 | # tests: [] 49 | # tags: [] 50 | 51 | # rule_tags: {} # Additional rule tags. 52 | 53 | # metrics: 54 | # quality_threshold: 25.0 55 | 56 | # github: 57 | # labels: [] 58 | # ignore_labels: 59 | # - sourcery-ignore 60 | # request_review: author 61 | # sourcery_branch: sourcery/{base_branch} 62 | 63 | # clone_detection: 64 | # min_lines: 3 65 | # min_duplicates: 2 66 | # identical_clones_only: false 67 | 68 | # proxy: 69 | # url: 70 | # ssl_certs_file: 71 | # no_ssl_verify: false -------------------------------------------------------------------------------- /AutoGpt.json: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct for auto-gpt 2 | 3 | ## 1. Purpose 4 | 5 | The purpose of this Code of Conduct is to provide guidelines for contributors to the auto-gpt project on GitHub. We aim to create a positive and inclusive environment where all participants can contribute and collaborate effectively. By participating in this project, you agree to abide by this Code of Conduct. 6 | 7 | ## 2. Scope 8 | 9 | This Code of Conduct applies to all contributors, maintainers, and users of the auto-gpt project. It extends to all project spaces, including but not limited to issues, pull requests, code reviews, comments, and other forms of communication within the project. 10 | 11 | ## 3. Our Standards 12 | 13 | We encourage the following behavior: 14 | 15 | * Being respectful and considerate to others 16 | * Actively seeking diverse perspectives 17 | * Providing constructive feedback and assistance 18 | * Demonstrating empathy and understanding 19 | 20 | We discourage the following behavior: 21 | 22 | * Harassment or discrimination of any kind 23 | * Disrespectful, offensive, or inappropriate language or content 24 | * Personal attacks or insults 25 | * Unwarranted criticism or negativity 26 | 27 | ## 4. Reporting and Enforcement 28 | 29 | If you witness or experience any violations of this Code of Conduct, please report them to the project maintainers by email or other appropriate means. The maintainers will investigate and take appropriate action, which may include warnings, temporary or permanent bans, or other measures as necessary. 30 | 31 | Maintainers are responsible for ensuring compliance with this Code of Conduct and may take action to address any violations. 32 | 33 | ## 5. Acknowledgements 34 | 35 | This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/version/2/0/code_of_conduct.html). 36 | 37 | ## 6. Contact 38 | 39 | If you have any questions or concerns, please contact the project maintainers. 40 | 41 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to ProjectName 2 | 3 | First of all, thank you for considering contributing to our project! We appreciate your time and effort, and we value any contribution, whether it's reporting a bug, suggesting a new feature, or submitting a pull request. 4 | 5 | This document provides guidelines and best practices to help you contribute effectively. 6 | 7 | ## Table of Contents 8 | 9 | - [Code of Conduct](#code-of-conduct) 10 | - [Getting Started](#getting-started) 11 | - [How to Contribute](#how-to-contribute) 12 | - [Reporting Bugs](#reporting-bugs) 13 | - [Suggesting Enhancements](#suggesting-enhancements) 14 | - [Submitting Pull Requests](#submitting-pull-requests) 15 | - [Style Guidelines](#style-guidelines) 16 | - [Code Formatting](#code-formatting) 17 | - [Pre-Commit Hooks](#pre-commit-hooks) 18 | 19 | ## Code of Conduct 20 | 21 | By participating in this project, you agree to abide by our [Code of Conduct](CODE_OF_CONDUCT.md). Please read it to understand the expectations we have for everyone who contributes to this project. 22 | 23 | ## Getting Started 24 | 25 | To start contributing, follow these steps: 26 | 27 | 1. Fork the repository and clone your fork. 28 | 2. Create a new branch for your changes (use a descriptive name, such as `fix-bug-123` or `add-new-feature`). 29 | 3. Make your changes in the new branch. 30 | 4. Test your changes thoroughly. 31 | 5. Commit and push your changes to your fork. 32 | 6. Create a pull request following the guidelines in the [Submitting Pull Requests](#submitting-pull-requests) section. 33 | 34 | ## How to Contribute 35 | 36 | ### Reporting Bugs 37 | 38 | If you find a bug in the project, please create an issue on GitHub with the following information: 39 | 40 | - A clear, descriptive title for the issue. 41 | - A description of the problem, including steps to reproduce the issue. 42 | - Any relevant logs, screenshots, or other supporting information. 43 | 44 | ### Suggesting Enhancements 45 | 46 | If you have an idea for a new feature or improvement, please create an issue on GitHub with the following information: 47 | 48 | - A clear, descriptive title for the issue. 49 | - A detailed description of the proposed enhancement, including any benefits and potential drawbacks. 50 | - Any relevant examples, mockups, or supporting information. 51 | 52 | ### Submitting Pull Requests 53 | 54 | When submitting a pull request, please ensure that your changes meet the following criteria: 55 | 56 | - Your pull request should be atomic and focus on a single change. 57 | - Your pull request should include tests for your change. 58 | - You should have thoroughly tested your changes with multiple different prompts. 59 | - You should have considered potential risks and mitigations for your changes. 60 | - You should have documented your changes clearly and comprehensively. 61 | - You should not include any unrelated or "extra" small tweaks or changes. 62 | 63 | ## Style Guidelines 64 | 65 | ### Code Formatting 66 | 67 | 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`: 68 | 69 | ```bash 70 | pip install black 71 | ``` 72 | 73 | To format your code, run the following command in the project's root directory: 74 | 75 | ```bash 76 | black . 77 | ``` 78 | ### Pre-Commit Hooks 79 | We use pre-commit hooks to ensure that code formatting and other checks are performed automatically before each commit. To set up pre-commit hooks for this project, follow these steps: 80 | 81 | Install the pre-commit package using pip: 82 | ```bash 83 | pip install pre-commit 84 | ``` 85 | 86 | Run the following command in the project's root directory to install the pre-commit hooks: 87 | ```bash 88 | pre-commit install 89 | ``` 90 | 91 | Now, the pre-commit hooks will run automatically before each commit, checking your code formatting and other requirements. 92 | 93 | 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. 94 | 95 | Happy coding, and once again, thank you for your contributions! 96 | 97 | 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: 98 | 99 | https://github.com/Torantulino/Auto-GPT/pulls?q=is%3Apr+is%3Aopen+-is%3Aconflict+ -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Use an official Python base image from the Docker Hub 2 | FROM python:3.11-slim 3 | 4 | # Install git 5 | RUN apt-get -y update 6 | RUN apt-get -y install git chromium-driver 7 | 8 | # Set environment variables 9 | ENV PIP_NO_CACHE_DIR=yes \ 10 | PYTHONUNBUFFERED=1 \ 11 | PYTHONDONTWRITEBYTECODE=1 12 | 13 | # Create a non-root user and set permissions 14 | RUN useradd --create-home appuser 15 | WORKDIR /home/appuser 16 | RUN chown appuser:appuser /home/appuser 17 | USER appuser 18 | 19 | # Copy the requirements.txt file and install the requirements 20 | COPY --chown=appuser:appuser requirements-docker.txt . 21 | RUN pip install --no-cache-dir --user -r requirements-docker.txt 22 | 23 | # Copy the application files 24 | COPY --chown=appuser:appuser autogpt/ ./autogpt 25 | 26 | # Set the entrypoint 27 | ENTRYPOINT ["python", "-m", "autogpt"] 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Toran Bruce Richards 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## 项目迁移至 https://github.com/kaqijiang/Auto-GPT-ZH 2 | -------------------------------------------------------------------------------- /autogpt/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaqijiang/Auto-GPT-aj/310a84c8ca0173c7db43f637866cf5677bd7ef50/autogpt/__init__.py -------------------------------------------------------------------------------- /autogpt/__main__.py: -------------------------------------------------------------------------------- 1 | """Main script for the autogpt package.""" 2 | import logging 3 | from colorama import Fore 4 | from autogpt.agent.agent import Agent 5 | from autogpt.args import parse_arguments 6 | 7 | from autogpt.config import Config, check_openai_api_key 8 | from autogpt.logs import logger 9 | from autogpt.memory import get_memory 10 | 11 | from autogpt.prompt import construct_prompt 12 | 13 | # Load environment variables from .env file 14 | 15 | 16 | def main() -> None: 17 | """Main function for the script""" 18 | cfg = Config() 19 | # TODO: fill in llm values here 20 | check_openai_api_key() 21 | parse_arguments() 22 | logger.set_level(logging.DEBUG if cfg.debug_mode else logging.INFO) 23 | ai_name = "" 24 | prompt = construct_prompt() 25 | # print(prompt) 26 | # Initialize variables 27 | full_message_history = [] 28 | next_action_count = 0 29 | # Make a constant: 30 | user_input = "确定要使用的下一个命令,并使用上面指定的格式进行响应:" 31 | # Initialize memory and make sure it is empty. 32 | # this is particularly important for indexing and referencing pinecone memory 33 | memory = get_memory(cfg, init=True) 34 | logger.typewriter_log( 35 | f"使用存储的类型:", Fore.GREEN, f"{memory.__class__.__name__}" 36 | ) 37 | logger.typewriter_log(f"使用浏览器:", Fore.GREEN, cfg.selenium_web_browser) 38 | agent = Agent( 39 | ai_name=ai_name, 40 | memory=memory, 41 | full_message_history=full_message_history, 42 | next_action_count=next_action_count, 43 | prompt=prompt, 44 | user_input=user_input, 45 | ) 46 | agent.start_interaction_loop() 47 | 48 | 49 | if __name__ == "__main__": 50 | main() 51 | -------------------------------------------------------------------------------- /autogpt/agent/__init__.py: -------------------------------------------------------------------------------- 1 | from autogpt.agent.agent import Agent 2 | from autogpt.agent.agent_manager import AgentManager 3 | 4 | __all__ = ["Agent", "AgentManager"] 5 | -------------------------------------------------------------------------------- /autogpt/agent/agent_manager.py: -------------------------------------------------------------------------------- 1 | """Agent manager for managing GPT agents""" 2 | from __future__ import annotations 3 | 4 | from autogpt.llm_utils import create_chat_completion 5 | from autogpt.config.config import Singleton 6 | 7 | 8 | class AgentManager(metaclass=Singleton): 9 | """Agent manager for managing GPT agents""" 10 | 11 | def __init__(self): 12 | self.next_key = 0 13 | self.agents = {} # key, (task, full_message_history, model) 14 | 15 | # Create new GPT agent 16 | # TODO: Centralise use of create_chat_completion() to globally enforce token limit 17 | 18 | def create_agent(self, task: str, prompt: str, model: str) -> tuple[int, str]: 19 | """Create a new agent and return its key 20 | 21 | Args: 22 | task: The task to perform 23 | prompt: The prompt to use 24 | model: The model to use 25 | 26 | Returns: 27 | The key of the new agent 28 | """ 29 | messages = [ 30 | {"role": "user", "content": prompt}, 31 | ] 32 | 33 | # Start GPT instance 34 | agent_reply = create_chat_completion( 35 | model=model, 36 | messages=messages, 37 | ) 38 | 39 | # Update full message history 40 | messages.append({"role": "assistant", "content": agent_reply}) 41 | 42 | key = self.next_key 43 | # This is done instead of len(agents) to make keys unique even if agents 44 | # are deleted 45 | self.next_key += 1 46 | 47 | self.agents[key] = (task, messages, model) 48 | 49 | return key, agent_reply 50 | 51 | def message_agent(self, key: str | int, message: str) -> str: 52 | """Send a message to an agent and return its response 53 | 54 | Args: 55 | key: The key of the agent to message 56 | message: The message to send to the agent 57 | 58 | Returns: 59 | The agent's response 60 | """ 61 | task, messages, model = self.agents[int(key)] 62 | 63 | # Add user message to message history before sending to agent 64 | messages.append({"role": "user", "content": message}) 65 | 66 | # Start GPT instance 67 | agent_reply = create_chat_completion( 68 | model=model, 69 | messages=messages, 70 | ) 71 | 72 | # Update full message history 73 | messages.append({"role": "assistant", "content": agent_reply}) 74 | 75 | return agent_reply 76 | 77 | def list_agents(self) -> list[tuple[str | int, str]]: 78 | """Return a list of all agents 79 | 80 | Returns: 81 | A list of tuples of the form (key, task) 82 | """ 83 | 84 | # Return a list of agent keys and their tasks 85 | return [(key, task) for key, (task, _, _) in self.agents.items()] 86 | 87 | def delete_agent(self, key: Union[str, int]) -> bool: 88 | """Delete an agent from the agent manager 89 | 90 | Args: 91 | key: The key of the agent to delete 92 | 93 | Returns: 94 | True if successful, False otherwise 95 | """ 96 | 97 | try: 98 | del self.agents[int(key)] 99 | return True 100 | except KeyError: 101 | return False 102 | -------------------------------------------------------------------------------- /autogpt/agent_manager.py: -------------------------------------------------------------------------------- 1 | from autogpt.llm_utils import create_chat_completion 2 | 3 | next_key = 0 4 | agents = {} # key, (task, full_message_history, model) 5 | 6 | # Create new GPT agent 7 | # TODO: Centralise use of create_chat_completion() to globally enforce token limit 8 | 9 | 10 | def create_agent(task, prompt, model): 11 | """创建新代理并返回其密钥""" 12 | global next_key 13 | global agents 14 | 15 | messages = [ 16 | {"role": "user", "content": prompt}, 17 | ] 18 | 19 | # Start GPT instance 20 | agent_reply = create_chat_completion( 21 | model=model, 22 | messages=messages, 23 | ) 24 | 25 | # Update full message history 26 | messages.append({"role": "assistant", "content": agent_reply}) 27 | 28 | key = next_key 29 | # This is done instead of len(agents) to make keys unique even if agents 30 | # are deleted 31 | next_key += 1 32 | 33 | agents[key] = (task, messages, model) 34 | 35 | return key, agent_reply 36 | 37 | 38 | def message_agent(key, message): 39 | """向代理发送消息并返回其响应""" 40 | global agents 41 | 42 | task, messages, model = agents[int(key)] 43 | 44 | # Add user message to message history before sending to agent 45 | messages.append({"role": "user", "content": message}) 46 | 47 | # Start GPT instance 48 | agent_reply = create_chat_completion( 49 | model=model, 50 | messages=messages, 51 | ) 52 | 53 | # Update full message history 54 | messages.append({"role": "assistant", "content": agent_reply}) 55 | 56 | return agent_reply 57 | 58 | 59 | def list_agents(): 60 | """返回所有代理的列表""" 61 | global agents 62 | 63 | # Return a list of agent keys and their tasks 64 | return [(key, task) for key, (task, _, _) in agents.items()] 65 | 66 | 67 | def delete_agent(key): 68 | """删除代理,如果成功则返回True,否则返回False""" 69 | global agents 70 | 71 | try: 72 | del agents[int(key)] 73 | return True 74 | except KeyError: 75 | return False 76 | -------------------------------------------------------------------------------- /autogpt/args.py: -------------------------------------------------------------------------------- 1 | """This module contains the argument parsing logic for the script.""" 2 | import argparse 3 | 4 | from colorama import Fore 5 | from autogpt import utils 6 | from autogpt.config import Config 7 | from autogpt.logs import logger 8 | from autogpt.memory import get_supported_memory_backends 9 | 10 | CFG = Config() 11 | 12 | 13 | def parse_arguments() -> None: 14 | """Parses the arguments passed to the script 15 | 16 | Returns: 17 | None 18 | """ 19 | CFG.set_debug_mode(False) 20 | CFG.set_continuous_mode(False) 21 | CFG.set_speak_mode(False) 22 | 23 | parser = argparse.ArgumentParser(description="Process arguments.") 24 | parser.add_argument( 25 | "--continuous", "-c", action="store_true", help="Enable Continuous Mode" 26 | ) 27 | parser.add_argument( 28 | "--continuous-limit", 29 | "-l", 30 | type=int, 31 | dest="continuous_limit", 32 | help="Defines the number of times to run in continuous mode", 33 | ) 34 | parser.add_argument("--speak", action="store_true", help="Enable Speak Mode") 35 | parser.add_argument("--debug", action="store_true", help="Enable Debug Mode") 36 | parser.add_argument( 37 | "--gpt3only", action="store_true", help="Enable GPT3.5 Only Mode" 38 | ) 39 | parser.add_argument("--gpt4only", action="store_true", help="Enable GPT4 Only Mode") 40 | parser.add_argument( 41 | "--use-memory", 42 | "-m", 43 | dest="memory_type", 44 | help="Defines which Memory backend to use", 45 | ) 46 | parser.add_argument( 47 | "--skip-reprompt", 48 | "-y", 49 | dest="skip_reprompt", 50 | action="store_true", 51 | help="Skips the re-prompting messages at the beginning of the script", 52 | ) 53 | parser.add_argument( 54 | "--use-browser", 55 | "-b", 56 | dest="browser_name", 57 | help="Specifies which web-browser to use when using selenium to scrape the web.", 58 | ) 59 | parser.add_argument( 60 | "--ai-settings", 61 | "-C", 62 | dest="ai_settings_file", 63 | help="Specifies which ai_settings.yaml file to use, will also automatically" 64 | " skip the re-prompt.", 65 | ) 66 | args = parser.parse_args() 67 | 68 | if args.debug: 69 | logger.typewriter_log("Debug Mode: ", Fore.GREEN, "ENABLED") 70 | CFG.set_debug_mode(True) 71 | 72 | if args.continuous: 73 | logger.typewriter_log("Continuous Mode: ", Fore.RED, "ENABLED") 74 | logger.typewriter_log( 75 | "WARNING: ", 76 | Fore.RED, 77 | "Continuous mode is not recommended. It is potentially dangerous and may" 78 | " cause your AI to run forever or carry out actions you would not usually" 79 | " authorise. Use at your own risk.", 80 | ) 81 | CFG.set_continuous_mode(True) 82 | 83 | if args.continuous_limit: 84 | logger.typewriter_log( 85 | "Continuous Limit: ", Fore.GREEN, f"{args.continuous_limit}" 86 | ) 87 | CFG.set_continuous_limit(args.continuous_limit) 88 | 89 | # Check if continuous limit is used without continuous mode 90 | if args.continuous_limit and not args.continuous: 91 | parser.error("--continuous-limit can only be used with --continuous") 92 | 93 | if args.speak: 94 | logger.typewriter_log("Speak Mode: ", Fore.GREEN, "ENABLED") 95 | CFG.set_speak_mode(True) 96 | 97 | if args.gpt3only: 98 | logger.typewriter_log("GPT3.5 Only Mode: ", Fore.GREEN, "ENABLED") 99 | CFG.set_smart_llm_model(CFG.fast_llm_model) 100 | 101 | if args.gpt4only: 102 | logger.typewriter_log("GPT4 Only Mode: ", Fore.GREEN, "ENABLED") 103 | CFG.set_fast_llm_model(CFG.smart_llm_model) 104 | 105 | if args.memory_type: 106 | supported_memory = get_supported_memory_backends() 107 | chosen = args.memory_type 108 | if chosen not in supported_memory: 109 | logger.typewriter_log( 110 | "ONLY THE FOLLOWING MEMORY BACKENDS ARE SUPPORTED: ", 111 | Fore.RED, 112 | f"{supported_memory}", 113 | ) 114 | logger.typewriter_log("Defaulting to: ", Fore.YELLOW, CFG.memory_backend) 115 | else: 116 | CFG.memory_backend = chosen 117 | 118 | if args.skip_reprompt: 119 | logger.typewriter_log("Skip Re-prompt: ", Fore.GREEN, "ENABLED") 120 | CFG.skip_reprompt = True 121 | 122 | if args.ai_settings_file: 123 | file = args.ai_settings_file 124 | 125 | # Validate file 126 | (validated, message) = utils.validate_yaml_file(file) 127 | if not validated: 128 | logger.typewriter_log("FAILED FILE VALIDATION", Fore.RED, message) 129 | logger.double_check() 130 | exit(1) 131 | 132 | logger.typewriter_log("Using AI Settings File:", Fore.GREEN, file) 133 | CFG.ai_settings_file = file 134 | CFG.skip_reprompt = True 135 | 136 | if args.browser_name: 137 | CFG.selenium_web_browser = args.browser_name 138 | -------------------------------------------------------------------------------- /autogpt/commands/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaqijiang/Auto-GPT-aj/310a84c8ca0173c7db43f637866cf5677bd7ef50/autogpt/commands/__init__.py -------------------------------------------------------------------------------- /autogpt/commands/audio_text.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | 4 | from autogpt.config import Config 5 | from autogpt.workspace import path_in_workspace 6 | 7 | cfg = Config() 8 | 9 | 10 | def read_audio_from_file(audio_path): 11 | audio_path = path_in_workspace(audio_path) 12 | with open(audio_path, "rb") as audio_file: 13 | audio = audio_file.read() 14 | return read_audio(audio) 15 | 16 | 17 | def read_audio(audio): 18 | model = cfg.huggingface_audio_to_text_model 19 | api_url = f"https://api-inference.huggingface.co/models/{model}" 20 | api_token = cfg.huggingface_api_token 21 | headers = {"Authorization": f"Bearer {api_token}"} 22 | 23 | if api_token is None: 24 | raise ValueError( 25 | "You need to set your Hugging Face API token in the config file." 26 | ) 27 | 28 | response = requests.post( 29 | api_url, 30 | headers=headers, 31 | data=audio, 32 | ) 33 | 34 | text = json.loads(response.content.decode("utf-8"))["text"] 35 | return "The audio says: " + text 36 | -------------------------------------------------------------------------------- /autogpt/commands/evaluate_code.py: -------------------------------------------------------------------------------- 1 | """Code evaluation module.""" 2 | from __future__ import annotations 3 | 4 | from autogpt.llm_utils import call_ai_function 5 | 6 | 7 | def evaluate_code(code: str) -> list[str]: 8 | """ 9 | A function that takes in a string and returns a response from create chat 10 | completion api call. 11 | 12 | Parameters: 13 | code (str): Code to be evaluated. 14 | Returns: 15 | A result string from create chat completion. A list of suggestions to 16 | improve the code. 17 | """ 18 | 19 | function_string = "def analyze_code(code: str) -> List[str]:" 20 | args = [code] 21 | description_string = ( 22 | "Analyzes the given code and returns a list of suggestions" " for improvements." 23 | ) 24 | 25 | return call_ai_function(function_string, args, description_string) 26 | -------------------------------------------------------------------------------- /autogpt/commands/execute_code.py: -------------------------------------------------------------------------------- 1 | """Execute code in a Docker container""" 2 | import os 3 | import subprocess 4 | 5 | import docker 6 | from docker.errors import ImageNotFound 7 | 8 | from autogpt.workspace import path_in_workspace, WORKSPACE_PATH 9 | 10 | 11 | def execute_python_file(file: str): 12 | """Execute a Python file in a Docker container and return the output 13 | 14 | Args: 15 | file (str): The name of the file to execute 16 | 17 | Returns: 18 | str: The output of the file 19 | """ 20 | 21 | print (f"正在工作空间 '{WORKSPACE_FOLDER}' 中执行文件 '{file}'") 22 | 23 | if not file.endswith(".py"): 24 | return "Error: 文件类型无效. 只允许 .py 文件." 25 | 26 | file_path = path_in_workspace(file) 27 | 28 | if not os.path.isfile(file_path): 29 | return f"Error: 文件 '{file}' 不存在." 30 | 31 | if we_are_running_in_a_docker_container(): 32 | result = subprocess.run( 33 | f"python {file_path}", capture_output=True, encoding="utf8", shell=True 34 | ) 35 | if result.returncode == 0: 36 | return result.stdout 37 | else: 38 | return f"Error: {result.stderr}" 39 | 40 | try: 41 | client = docker.from_env() 42 | 43 | image_name = "python:3.10" 44 | try: 45 | client.images.get(image_name) 46 | print(f"Image '{image_name}' found locally") 47 | except ImageNotFound: 48 | print(f"在本地找不到图像'{image_name}',从 Docker Hub 拉取") 49 | # Use the low-level API to stream the pull response 50 | low_level_client = docker.APIClient() 51 | for line in low_level_client.pull(image_name, stream=True, decode=True): 52 | # Print the status and progress, if available 53 | status = line.get("status") 54 | progress = line.get("progress") 55 | if status and progress: 56 | print(f"{status}: {progress}") 57 | elif status: 58 | print(status) 59 | 60 | # You can replace 'python:3.8' with the desired Python image/version 61 | # You can find available Python images on Docker Hub: 62 | # https://hub.docker.com/_/python 63 | container = client.containers.run( 64 | image_name, 65 | f"python {file}", 66 | volumes={ 67 | os.path.abspath(WORKSPACE_PATH): { 68 | "bind": "/workspace", 69 | "mode": "ro", 70 | } 71 | }, 72 | working_dir="/workspace", 73 | stderr=True, 74 | stdout=True, 75 | detach=True, 76 | ) 77 | 78 | container.wait() 79 | logs = container.logs().decode("utf-8") 80 | container.remove() 81 | 82 | # print(f"Execution complete. Output: {output}") 83 | # print(f"Logs: {logs}") 84 | 85 | return logs 86 | 87 | except Exception as e: 88 | return f"Error: {str(e)}" 89 | 90 | 91 | def execute_shell(command_line: str) -> str: 92 | """Execute a shell command and return the output 93 | 94 | Args: 95 | command_line (str): The command line to execute 96 | 97 | Returns: 98 | str: The output of the command 99 | """ 100 | current_dir = os.getcwd() 101 | # Change dir into workspace if necessary 102 | if str(WORKSPACE_PATH) not in current_dir: 103 | os.chdir(WORKSPACE_PATH) 104 | 105 | print(f"正在工作目录'{os.getcwd()}'中执行命令'{command_line}'") 106 | 107 | result = subprocess.run(command_line, capture_output=True, shell=True) 108 | output = f"STDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}" 109 | 110 | # Change back to whatever the prior working dir was 111 | 112 | os.chdir(current_dir) 113 | 114 | return output 115 | 116 | 117 | def we_are_running_in_a_docker_container() -> bool: 118 | """Check if we are running in a Docker container 119 | 120 | Returns: 121 | bool: True if we are running in a Docker container, False otherwise 122 | """ 123 | return os.path.exists("/.dockerenv") 124 | -------------------------------------------------------------------------------- /autogpt/commands/git_operations.py: -------------------------------------------------------------------------------- 1 | """Git operations for autogpt""" 2 | import git 3 | from autogpt.config import Config 4 | 5 | CFG = Config() 6 | 7 | 8 | def clone_repository(repo_url: str, clone_path: str) -> str: 9 | """Clone a github repository locally 10 | 11 | Args: 12 | repo_url (str): The URL of the repository to clone 13 | clone_path (str): The path to clone the repository to 14 | 15 | Returns: 16 | str: The result of the clone operation""" 17 | split_url = repo_url.split("//") 18 | auth_repo_url = f"//{CFG.github_username}:{CFG.github_api_key}@".join(split_url) 19 | try: 20 | git.Repo.clone_from(auth_repo_url, clone_path) 21 | return f"""Cloned {repo_url} to {clone_path}""" 22 | except Exception as e: 23 | return f"Error: {str(e)}" 24 | -------------------------------------------------------------------------------- /autogpt/commands/google_search.py: -------------------------------------------------------------------------------- 1 | """Google search command for Autogpt.""" 2 | from __future__ import annotations 3 | 4 | import json 5 | 6 | from duckduckgo_search import ddg 7 | 8 | from autogpt.config import Config 9 | 10 | CFG = Config() 11 | 12 | 13 | def google_search(query: str, num_results: int = 8) -> str: 14 | """Return the results of a google search 15 | 16 | Args: 17 | query (str): The search query. 18 | num_results (int): The number of results to return. 19 | 20 | Returns: 21 | str: The results of the search. 22 | """ 23 | search_results = [] 24 | if not query: 25 | return json.dumps(search_results) 26 | 27 | results = ddg(query, max_results=num_results) 28 | if not results: 29 | return json.dumps(search_results) 30 | 31 | for j in results: 32 | search_results.append(j) 33 | 34 | return json.dumps(search_results, ensure_ascii=False, indent=4) 35 | 36 | 37 | def google_official_search(query: str, num_results: int = 8) -> str | list[str]: 38 | """Return the results of a google search using the official Google API 39 | 40 | Args: 41 | query (str): The search query. 42 | num_results (int): The number of results to return. 43 | 44 | Returns: 45 | str: The results of the search. 46 | """ 47 | 48 | from googleapiclient.discovery import build 49 | from googleapiclient.errors import HttpError 50 | 51 | try: 52 | # Get the Google API key and Custom Search Engine ID from the config file 53 | api_key = CFG.google_api_key 54 | custom_search_engine_id = CFG.custom_search_engine_id 55 | 56 | # Initialize the Custom Search API service 57 | service = build("customsearch", "v1", developerKey=api_key) 58 | 59 | # Send the search query and retrieve the results 60 | result = ( 61 | service.cse() 62 | .list(q=query, cx=custom_search_engine_id, num=num_results) 63 | .execute() 64 | ) 65 | 66 | # Extract the search result items from the response 67 | search_results = result.get("items", []) 68 | 69 | # Create a list of only the URLs from the search results 70 | search_results_links = [item["link"] for item in search_results] 71 | 72 | except HttpError as e: 73 | # Handle errors in the API call 74 | error_details = json.loads(e.content.decode()) 75 | 76 | # Check if the error is related to an invalid or missing API key 77 | if error_details.get("error", {}).get( 78 | "code" 79 | ) == 403 and "invalid API key" in error_details.get("error", {}).get( 80 | "message", "" 81 | ): 82 | return "Error: The provided Google API key is invalid or missing." 83 | else: 84 | return f"Error: {e}" 85 | 86 | # Return the list of search result URLs 87 | return search_results_links 88 | -------------------------------------------------------------------------------- /autogpt/commands/image_gen.py: -------------------------------------------------------------------------------- 1 | """ Image Generation Module for AutoGPT.""" 2 | import io 3 | import os.path 4 | import uuid 5 | from base64 import b64decode 6 | 7 | import openai 8 | import requests 9 | from PIL import Image 10 | from autogpt.config import Config 11 | from autogpt.workspace import path_in_workspace 12 | 13 | CFG = Config() 14 | 15 | 16 | def generate_image(prompt: str) -> str: 17 | """Generate an image from a prompt. 18 | 19 | Args: 20 | prompt (str): The prompt to use 21 | 22 | Returns: 23 | str: The filename of the image 24 | """ 25 | filename = f"{str(uuid.uuid4())}.jpg" 26 | 27 | # DALL-E 28 | if CFG.image_provider == "dalle": 29 | return generate_image_with_dalle(prompt, filename) 30 | elif CFG.image_provider == "sd": 31 | return generate_image_with_hf(prompt, filename) 32 | else: 33 | return "No Image Provider Set" 34 | 35 | 36 | def generate_image_with_hf(prompt: str, filename: str) -> str: 37 | """Generate an image with HuggingFace's API. 38 | 39 | Args: 40 | prompt (str): The prompt to use 41 | filename (str): The filename to save the image to 42 | 43 | Returns: 44 | str: The filename of the image 45 | """ 46 | API_URL = ( 47 | "https://api-inference.huggingface.co/models/CompVis/stable-diffusion-v1-4" 48 | ) 49 | if CFG.huggingface_api_token is None: 50 | raise ValueError( 51 | "You need to set your Hugging Face API token in the config file." 52 | ) 53 | headers = {"Authorization": f"Bearer {CFG.huggingface_api_token}"} 54 | 55 | response = requests.post( 56 | API_URL, 57 | headers=headers, 58 | json={ 59 | "inputs": prompt, 60 | }, 61 | ) 62 | 63 | image = Image.open(io.BytesIO(response.content)) 64 | print(f"Image Generated for prompt:{prompt}") 65 | 66 | image.save(path_in_workspace(filename)) 67 | 68 | return f"Saved to disk:{filename}" 69 | 70 | 71 | def generate_image_with_dalle(prompt: str, filename: str) -> str: 72 | """Generate an image with DALL-E. 73 | 74 | Args: 75 | prompt (str): The prompt to use 76 | filename (str): The filename to save the image to 77 | 78 | Returns: 79 | str: The filename of the image 80 | """ 81 | openai.api_key = CFG.openai_api_key 82 | 83 | response = openai.Image.create( 84 | prompt=prompt, 85 | n=1, 86 | size="256x256", 87 | response_format="b64_json", 88 | ) 89 | 90 | print(f"Image Generated for prompt:{prompt}") 91 | 92 | image_data = b64decode(response["data"][0]["b64_json"]) 93 | 94 | with open(path_in_workspace(filename), mode="wb") as png: 95 | png.write(image_data) 96 | 97 | return f"Saved to disk:{filename}" 98 | -------------------------------------------------------------------------------- /autogpt/commands/improve_code.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import json 4 | 5 | from autogpt.llm_utils import call_ai_function 6 | 7 | 8 | def improve_code(suggestions: list[str], code: str) -> str: 9 | """ 10 | A function that takes in code and suggestions and returns a response from create 11 | chat completion api call. 12 | 13 | Parameters: 14 | suggestions (List): A list of suggestions around what needs to be improved. 15 | code (str): Code to be improved. 16 | Returns: 17 | A result string from create chat completion. Improved code in response. 18 | """ 19 | 20 | function_string = ( 21 | "def generate_improved_code(suggestions: List[str], code: str) -> str:" 22 | ) 23 | args = [json.dumps(suggestions), code] 24 | description_string = ( 25 | "Improves the provided code based on the suggestions" 26 | " provided, making no other changes." 27 | ) 28 | 29 | return call_ai_function(function_string, args, description_string) 30 | -------------------------------------------------------------------------------- /autogpt/commands/times.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | 4 | def get_datetime() -> str: 5 | """Return the current date and time 6 | 7 | Returns: 8 | str: The current date and time 9 | """ 10 | return "Current date and time: " + datetime.now().strftime("%Y-%m-%d %H:%M:%S") 11 | -------------------------------------------------------------------------------- /autogpt/commands/twitter.py: -------------------------------------------------------------------------------- 1 | import tweepy 2 | import os 3 | from dotenv import load_dotenv 4 | 5 | load_dotenv() 6 | 7 | 8 | def send_tweet(tweet_text): 9 | consumer_key = os.environ.get("TW_CONSUMER_KEY") 10 | consumer_secret = os.environ.get("TW_CONSUMER_SECRET") 11 | access_token = os.environ.get("TW_ACCESS_TOKEN") 12 | access_token_secret = os.environ.get("TW_ACCESS_TOKEN_SECRET") 13 | # Authenticate to Twitter 14 | auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 15 | auth.set_access_token(access_token, access_token_secret) 16 | 17 | # Create API object 18 | api = tweepy.API(auth) 19 | 20 | # Send tweet 21 | try: 22 | api.update_status(tweet_text) 23 | print("Tweet sent successfully!") 24 | except tweepy.TweepyException as e: 25 | print("Error sending tweet: {}".format(e.reason)) 26 | -------------------------------------------------------------------------------- /autogpt/commands/web_playwright.py: -------------------------------------------------------------------------------- 1 | """Web scraping commands using Playwright""" 2 | from __future__ import annotations 3 | 4 | try: 5 | from playwright.sync_api import sync_playwright 6 | except ImportError: 7 | print( 8 | "Playwright not installed. Please install it with 'pip install playwright' to use." 9 | ) 10 | from bs4 import BeautifulSoup 11 | from autogpt.processing.html import extract_hyperlinks, format_hyperlinks 12 | 13 | 14 | def scrape_text(url: str) -> str: 15 | """Scrape text from a webpage 16 | 17 | Args: 18 | url (str): The URL to scrape text from 19 | 20 | Returns: 21 | str: The scraped text 22 | """ 23 | with sync_playwright() as p: 24 | browser = p.chromium.launch() 25 | page = browser.new_page() 26 | 27 | try: 28 | page.goto(url) 29 | html_content = page.content() 30 | soup = BeautifulSoup(html_content, "html.parser") 31 | 32 | for script in soup(["script", "style"]): 33 | script.extract() 34 | 35 | text = soup.get_text() 36 | lines = (line.strip() for line in text.splitlines()) 37 | chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) 38 | text = "\n".join(chunk for chunk in chunks if chunk) 39 | 40 | except Exception as e: 41 | text = f"Error: {str(e)}" 42 | 43 | finally: 44 | browser.close() 45 | 46 | return text 47 | 48 | 49 | def scrape_links(url: str) -> str | list[str]: 50 | """Scrape links from a webpage 51 | 52 | Args: 53 | url (str): The URL to scrape links from 54 | 55 | Returns: 56 | Union[str, List[str]]: The scraped links 57 | """ 58 | with sync_playwright() as p: 59 | browser = p.chromium.launch() 60 | page = browser.new_page() 61 | 62 | try: 63 | page.goto(url) 64 | html_content = page.content() 65 | soup = BeautifulSoup(html_content, "html.parser") 66 | 67 | for script in soup(["script", "style"]): 68 | script.extract() 69 | 70 | hyperlinks = extract_hyperlinks(soup, url) 71 | formatted_links = format_hyperlinks(hyperlinks) 72 | 73 | except Exception as e: 74 | formatted_links = f"Error: {str(e)}" 75 | 76 | finally: 77 | browser.close() 78 | 79 | return formatted_links 80 | -------------------------------------------------------------------------------- /autogpt/commands/web_selenium.py: -------------------------------------------------------------------------------- 1 | """Selenium web scraping module.""" 2 | from __future__ import annotations 3 | 4 | from selenium import webdriver 5 | from autogpt.processing.html import extract_hyperlinks, format_hyperlinks 6 | import autogpt.processing.text as summary 7 | from bs4 import BeautifulSoup 8 | from selenium.webdriver.remote.webdriver import WebDriver 9 | from selenium.webdriver.common.by import By 10 | from selenium.webdriver.support.wait import WebDriverWait 11 | from selenium.webdriver.support import expected_conditions as EC 12 | from webdriver_manager.chrome import ChromeDriverManager 13 | from webdriver_manager.firefox import GeckoDriverManager 14 | from selenium.webdriver.chrome.options import Options as ChromeOptions 15 | from selenium.webdriver.firefox.options import Options as FirefoxOptions 16 | from selenium.webdriver.safari.options import Options as SafariOptions 17 | import logging 18 | from pathlib import Path 19 | from autogpt.config import Config 20 | 21 | FILE_DIR = Path(__file__).parent.parent 22 | CFG = Config() 23 | 24 | 25 | def browse_website(url: str, question: str) -> tuple[str, WebDriver]: 26 | """Browse a website and return the answer and links to the user 27 | 28 | Args: 29 | url (str): The url of the website to browse 30 | question (str): The question asked by the user 31 | 32 | Returns: 33 | Tuple[str, WebDriver]: The answer and links to the user and the webdriver 34 | """ 35 | driver, text = scrape_text_with_selenium(url) 36 | add_header(driver) 37 | summary_text = summary.summarize_text(url, text, question, driver) 38 | links = scrape_links_with_selenium(driver, url) 39 | 40 | # Limit links to 5 41 | if len(links) > 5: 42 | links = links[:5] 43 | close_browser(driver) 44 | return f"Answer gathered from website: {summary_text} \n \n Links: {links}", driver 45 | 46 | 47 | def scrape_text_with_selenium(url: str) -> tuple[WebDriver, str]: 48 | """Scrape text from a website using selenium 49 | 50 | Args: 51 | url (str): The url of the website to scrape 52 | 53 | Returns: 54 | Tuple[WebDriver, str]: The webdriver and the text scraped from the website 55 | """ 56 | logging.getLogger("selenium").setLevel(logging.CRITICAL) 57 | 58 | options_available = { 59 | "chrome": ChromeOptions, 60 | "safari": SafariOptions, 61 | "firefox": FirefoxOptions, 62 | } 63 | 64 | options = options_available[CFG.selenium_web_browser]() 65 | options.add_argument( 66 | "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" 67 | ) 68 | 69 | if CFG.selenium_web_browser == "firefox": 70 | driver = webdriver.Firefox( 71 | executable_path=GeckoDriverManager().install(), options=options 72 | ) 73 | elif CFG.selenium_web_browser == "safari": 74 | # Requires a bit more setup on the users end 75 | # See https://developer.apple.com/documentation/webkit/testing_with_webdriver_in_safari 76 | driver = webdriver.Safari(options=options) 77 | else: 78 | driver = webdriver.Chrome( 79 | executable_path=ChromeDriverManager().install(), options=options 80 | ) 81 | driver.get(url) 82 | 83 | WebDriverWait(driver, 10).until( 84 | EC.presence_of_element_located((By.TAG_NAME, "body")) 85 | ) 86 | 87 | # Get the HTML content directly from the browser's DOM 88 | page_source = driver.execute_script("return document.body.outerHTML;") 89 | soup = BeautifulSoup(page_source, "html.parser") 90 | 91 | for script in soup(["script", "style"]): 92 | script.extract() 93 | 94 | text = soup.get_text() 95 | lines = (line.strip() for line in text.splitlines()) 96 | chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) 97 | text = "\n".join(chunk for chunk in chunks if chunk) 98 | return driver, text 99 | 100 | 101 | def scrape_links_with_selenium(driver: WebDriver, url: str) -> list[str]: 102 | """Scrape links from a website using selenium 103 | 104 | Args: 105 | driver (WebDriver): The webdriver to use to scrape the links 106 | 107 | Returns: 108 | List[str]: The links scraped from the website 109 | """ 110 | page_source = driver.page_source 111 | soup = BeautifulSoup(page_source, "html.parser") 112 | 113 | for script in soup(["script", "style"]): 114 | script.extract() 115 | 116 | hyperlinks = extract_hyperlinks(soup, url) 117 | 118 | return format_hyperlinks(hyperlinks) 119 | 120 | 121 | def close_browser(driver: WebDriver) -> None: 122 | """Close the browser 123 | 124 | Args: 125 | driver (WebDriver): The webdriver to close 126 | 127 | Returns: 128 | None 129 | """ 130 | driver.quit() 131 | 132 | 133 | def add_header(driver: WebDriver) -> None: 134 | """Add a header to the website 135 | 136 | Args: 137 | driver (WebDriver): The webdriver to use to add the header 138 | 139 | Returns: 140 | None 141 | """ 142 | driver.execute_script(open(f"{FILE_DIR}/js/overlay.js", "r").read()) 143 | -------------------------------------------------------------------------------- /autogpt/commands/write_tests.py: -------------------------------------------------------------------------------- 1 | """A module that contains a function to generate test cases for the submitted code.""" 2 | from __future__ import annotations 3 | 4 | import json 5 | from autogpt.llm_utils import call_ai_function 6 | 7 | 8 | def write_tests(code: str, focus: list[str]) -> str: 9 | """ 10 | A function that takes in code and focus topics and returns a response from create 11 | chat completion api call. 12 | 13 | Parameters: 14 | focus (list): A list of suggestions around what needs to be improved. 15 | code (str): Code for test cases to be generated against. 16 | Returns: 17 | A result string from create chat completion. Test cases for the submitted code 18 | in response. 19 | """ 20 | 21 | function_string = ( 22 | "def create_test_cases(code: str, focus: Optional[str] = None) -> str:" 23 | ) 24 | args = [code, json.dumps(focus)] 25 | description_string = ( 26 | "Generates test cases for the existing code, focusing on" 27 | " specific areas if required." 28 | ) 29 | 30 | return call_ai_function(function_string, args, description_string) 31 | -------------------------------------------------------------------------------- /autogpt/config/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | This module contains the configuration classes for AutoGPT. 3 | """ 4 | from autogpt.config.ai_config import AIConfig 5 | from autogpt.config.config import check_openai_api_key, Config 6 | from autogpt.config.singleton import AbstractSingleton, Singleton 7 | 8 | __all__ = [ 9 | "check_openai_api_key", 10 | "AbstractSingleton", 11 | "AIConfig", 12 | "Config", 13 | "Singleton", 14 | ] 15 | -------------------------------------------------------------------------------- /autogpt/config/ai_config.py: -------------------------------------------------------------------------------- 1 | # sourcery skip: do-not-use-staticmethod 2 | """ 3 | A module that contains the AIConfig class object that contains the configuration 4 | """ 5 | from __future__ import annotations 6 | 7 | import os 8 | from typing import Type 9 | import yaml 10 | 11 | 12 | class AIConfig: 13 | """ 14 | A class object that contains the configuration information for the AI 15 | 16 | Attributes: 17 | ai_name (str): The name of the AI. 18 | ai_role (str): The description of the AI's role. 19 | ai_goals (list): The list of objectives the AI is supposed to complete. 20 | """ 21 | 22 | def __init__( 23 | self, ai_name: str = "", ai_role: str = "", ai_goals: list | None = None 24 | ) -> None: 25 | """ 26 | Initialize a class instance 27 | 28 | Parameters: 29 | ai_name (str): The name of the AI. 30 | ai_role (str): The description of the AI's role. 31 | ai_goals (list): The list of objectives the AI is supposed to complete. 32 | Returns: 33 | None 34 | """ 35 | if ai_goals is None: 36 | ai_goals = [] 37 | self.ai_name = ai_name 38 | self.ai_role = ai_role 39 | self.ai_goals = ai_goals 40 | 41 | # Soon this will go in a folder where it remembers more stuff about the run(s) 42 | SAVE_FILE = os.path.join(os.path.dirname(__file__), "..", "ai_settings.yaml") 43 | 44 | @staticmethod 45 | def load(config_file: str = SAVE_FILE) -> "AIConfig": 46 | """ 47 | Returns class object with parameters (ai_name, ai_role, ai_goals) loaded from 48 | yaml file if yaml file exists, 49 | else returns class with no parameters. 50 | 51 | Parameters: 52 | config_file (int): The path to the config yaml file. 53 | DEFAULT: "../ai_settings.yaml" 54 | 55 | Returns: 56 | cls (object): An instance of given cls object 57 | """ 58 | 59 | try: 60 | with open(config_file, encoding="utf-8") as file: 61 | config_params = yaml.load(file, Loader=yaml.FullLoader) 62 | except FileNotFoundError: 63 | config_params = {} 64 | 65 | ai_name = config_params.get("ai_name", "") 66 | ai_role = config_params.get("ai_role", "") 67 | ai_goals = config_params.get("ai_goals", []) 68 | # type: Type[AIConfig] 69 | return AIConfig(ai_name, ai_role, ai_goals) 70 | 71 | def save(self, config_file: str = SAVE_FILE) -> None: 72 | """ 73 | Saves the class parameters to the specified file yaml file path as a yaml file. 74 | 75 | Parameters: 76 | config_file(str): The path to the config yaml file. 77 | DEFAULT: "../ai_settings.yaml" 78 | 79 | Returns: 80 | None 81 | """ 82 | 83 | config = { 84 | "ai_name": self.ai_name, 85 | "ai_role": self.ai_role, 86 | "ai_goals": self.ai_goals, 87 | } 88 | with open(config_file, "w", encoding="utf-8") as file: 89 | yaml.dump(config, file, allow_unicode=True) 90 | 91 | def construct_full_prompt(self) -> str: 92 | """ 93 | Returns a prompt to the user with the class information in an organized fashion. 94 | 95 | Parameters: 96 | None 97 | 98 | Returns: 99 | full_prompt (str): A string containing the initial prompt for the user 100 | including the ai_name, ai_role and ai_goals. 101 | """ 102 | 103 | prompt_start = ( 104 | "Your decisions must always be made independently without" 105 | " seeking user assistance. Play to your strengths as an LLM and pursue" 106 | " simple strategies with no legal complications." 107 | "" 108 | ) 109 | 110 | from autogpt.prompt import get_prompt 111 | 112 | # Construct full prompt 113 | full_prompt = ( 114 | f"You are {self.ai_name}, {self.ai_role}\n{prompt_start}\n\nGOALS:\n\n" 115 | ) 116 | for i, goal in enumerate(self.ai_goals): 117 | full_prompt += f"{i+1}. {goal}\n" 118 | 119 | full_prompt += f"\n\n{get_prompt()}" 120 | return full_prompt 121 | -------------------------------------------------------------------------------- /autogpt/config/singleton.py: -------------------------------------------------------------------------------- 1 | """The singleton metaclass for ensuring only one instance of a class.""" 2 | import abc 3 | 4 | 5 | class Singleton(abc.ABCMeta, type): 6 | """ 7 | Singleton metaclass for ensuring only one instance of a class. 8 | """ 9 | 10 | _instances = {} 11 | 12 | def __call__(cls, *args, **kwargs): 13 | """Call method for the singleton metaclass.""" 14 | if cls not in cls._instances: 15 | cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) 16 | return cls._instances[cls] 17 | 18 | 19 | class AbstractSingleton(abc.ABC, metaclass=Singleton): 20 | """ 21 | Abstract singleton class for ensuring only one instance of a class. 22 | """ 23 | 24 | pass 25 | -------------------------------------------------------------------------------- /autogpt/data_ingestion.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import logging 3 | 4 | from autogpt.config import Config 5 | from autogpt.commands.file_operations import ingest_file, search_files 6 | from autogpt.memory import get_memory 7 | 8 | cfg = Config() 9 | 10 | 11 | def configure_logging(): 12 | logging.basicConfig( 13 | filename="log-ingestion.txt", 14 | filemode="a", 15 | format="%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s", 16 | datefmt="%H:%M:%S", 17 | level=logging.DEBUG, 18 | ) 19 | return logging.getLogger("AutoGPT-Ingestion") 20 | 21 | 22 | def ingest_directory(directory, memory, args): 23 | """ 24 | 通过为每个文件调用 ingest_file 函数来摄取目录中的所有文件。 25 | 26 | :param directory: 包含要摄取的文件的目录 27 | :param memory: 具有 add() 方法的对象,用于将块存储在内存中 28 | """ 29 | try: 30 | files = search_files(directory) 31 | for file in files: 32 | ingest_file(file, memory, args.max_length, args.overlap) 33 | except Exception as e: 34 | print(f"获取目录 '{directory}' 时出错:{str(e)}") 35 | 36 | 37 | def main() -> None: 38 | logger = configure_logging() 39 | 40 | parser = argparse.ArgumentParser( 41 | description="Ingest a file or a directory with multiple files into memory. " 42 | "Make sure to set your .env before running this script." 43 | ) 44 | group = parser.add_mutually_exclusive_group(required=True) 45 | group.add_argument("--file", type=str, help="The file to ingest.") 46 | group.add_argument( 47 | "--dir", type=str, help="The directory containing the files to ingest." 48 | ) 49 | parser.add_argument( 50 | "--init", 51 | action="store_true", 52 | help="Init the memory and wipe its content (default: False)", 53 | default=False, 54 | ) 55 | parser.add_argument( 56 | "--overlap", 57 | type=int, 58 | help="The overlap size between chunks when ingesting files (default: 200)", 59 | default=200, 60 | ) 61 | parser.add_argument( 62 | "--max_length", 63 | type=int, 64 | help="The max_length of each chunk when ingesting files (default: 4000)", 65 | default=4000, 66 | ) 67 | 68 | args = parser.parse_args() 69 | 70 | # Initialize memory 71 | memory = get_memory(cfg, init=args.init) 72 | print("使用内存类型:" + memory.__class__.__name__) 73 | 74 | if args.file: 75 | try: 76 | ingest_file(args.file, memory, args.max_length, args.overlap) 77 | print(f"文件 '{args.file}' 已成功获取。") 78 | except Exception as e: 79 | logger.error(f"获取文件 '{args.file}' 时出错:{str(e)}") 80 | print(f"获取文件 '{args.file}' 时出错:{str(e)}") 81 | elif args.dir: 82 | try: 83 | ingest_directory(args.dir, memory, args) 84 | print(f"目录 '{args.dir}' 成功获取。") 85 | except Exception as e: 86 | logger.error(f"获取目录 '{args.dir}' 时出错:{str(e)}") 87 | print(f"获取目录 '{args.dir}' 时出错:{str(e)}") 88 | else: 89 | print( 90 | "请提供 auto_gpt_workspace 目录中的文件路径 (--file) 或目录名称 (--dir) 作为输入。" 91 | ) 92 | 93 | 94 | if __name__ == "__main__": 95 | main() 96 | -------------------------------------------------------------------------------- /autogpt/file_operations.py: -------------------------------------------------------------------------------- 1 | import os 2 | import os.path 3 | 4 | # Set a dedicated folder for file I/O 5 | working_directory = "auto_gpt_workspace" 6 | 7 | # Create the directory if it doesn't exist 8 | if not os.path.exists(working_directory): 9 | os.makedirs(working_directory) 10 | 11 | 12 | def safe_join(base, *paths): 13 | """Join one or more path components intelligently.""" 14 | new_path = os.path.join(base, *paths) 15 | norm_new_path = os.path.normpath(new_path) 16 | 17 | if os.path.commonprefix([base, norm_new_path]) != base: 18 | raise ValueError("尝试访问工作目录之外的位置。") 19 | 20 | return norm_new_path 21 | 22 | 23 | def split_file(content, max_length=4000, overlap=0): 24 | """ 25 | Split text into chunks of a specified maximum length with a specified overlap 26 | between chunks. 27 | 28 | :param text: The input text to be split into chunks 29 | :param max_length: The maximum length of each chunk, 30 | default is 4000 (about 1k token) 31 | :param overlap: The number of overlapping characters between chunks, 32 | default is no overlap 33 | :return: A generator yielding chunks of text 34 | """ 35 | start = 0 36 | content_length = len(content) 37 | 38 | while start < content_length: 39 | end = start + max_length 40 | if end + overlap < content_length: 41 | chunk = content[start : end + overlap] 42 | else: 43 | chunk = content[start:content_length] 44 | yield chunk 45 | start += max_length - overlap 46 | 47 | 48 | def read_file(filename) -> str: 49 | """Read a file and return the contents""" 50 | try: 51 | filepath = safe_join(working_directory, filename) 52 | with open(filepath, "r", encoding="utf-8") as f: 53 | content = f.read() 54 | return content 55 | except Exception as e: 56 | return f"Error: {str(e)}" 57 | 58 | 59 | def ingest_file(filename, memory, max_length=4000, overlap=200): 60 | """ 61 | Ingest a file by reading its content, splitting it into chunks with a specified 62 | maximum length and overlap, and adding the chunks to the memory storage. 63 | 64 | :param filename: The name of the file to ingest 65 | :param memory: An object with an add() method to store the chunks in memory 66 | :param max_length: The maximum length of each chunk, default is 4000 67 | :param overlap: The number of overlapping characters between chunks, default is 200 68 | """ 69 | try: 70 | print(f"Working with file {filename}") 71 | content = read_file(filename) 72 | content_length = len(content) 73 | print(f"File length: {content_length} characters") 74 | 75 | chunks = list(split_file(content, max_length=max_length, overlap=overlap)) 76 | 77 | num_chunks = len(chunks) 78 | for i, chunk in enumerate(chunks): 79 | print(f"正在摄取块 {i + 1} / {num_chunks} 到内存中") 80 | memory_to_add = ( 81 | f"Filename: {filename}\n" f"Content part#{i + 1}/{num_chunks}: {chunk}" 82 | ) 83 | 84 | memory.add(memory_to_add) 85 | 86 | print(f"完成从 {filename} 摄取 {num_chunks}个chunk.") 87 | except Exception as e: 88 | print(f"Error: 摄取文件时 '{filename}': {str(e)}") 89 | 90 | 91 | def write_to_file(filename, text): 92 | """Write text to a file""" 93 | try: 94 | filepath = safe_join(working_directory, filename) 95 | directory = os.path.dirname(filepath) 96 | if not os.path.exists(directory): 97 | os.makedirs(directory) 98 | with open(filepath, "w", encoding="utf-8") as f: 99 | f.write(text) 100 | return "文件写入成功。" 101 | except Exception as e: 102 | return "Error: " + str(e) 103 | 104 | 105 | def append_to_file(filename, text): 106 | """Append text to a file""" 107 | try: 108 | filepath = safe_join(working_directory, filename) 109 | with open(filepath, "a") as f: 110 | f.write(text) 111 | return "已成功添加文本." 112 | except Exception as e: 113 | return "Error: " + str(e) 114 | 115 | 116 | def delete_file(filename): 117 | """Delete a file""" 118 | try: 119 | filepath = safe_join(working_directory, filename) 120 | os.remove(filepath) 121 | return "文件删除成功." 122 | except Exception as e: 123 | return "Error: " + str(e) 124 | 125 | 126 | def search_files(directory): 127 | found_files = [] 128 | 129 | if directory == "" or directory == "/": 130 | search_directory = working_directory 131 | else: 132 | search_directory = safe_join(working_directory, directory) 133 | 134 | for root, _, files in os.walk(search_directory): 135 | for file in files: 136 | if file.startswith("."): 137 | continue 138 | relative_path = os.path.relpath(os.path.join(root, file), working_directory) 139 | found_files.append(relative_path) 140 | 141 | return found_files 142 | -------------------------------------------------------------------------------- /autogpt/image_gen.py: -------------------------------------------------------------------------------- 1 | import io 2 | import os.path 3 | import uuid 4 | from base64 import b64decode 5 | 6 | import openai 7 | import requests 8 | from PIL import Image 9 | 10 | from autogpt.config import Config 11 | 12 | cfg = Config() 13 | 14 | working_directory = "auto_gpt_workspace" 15 | 16 | 17 | def generate_image(prompt): 18 | filename = str(uuid.uuid4()) + ".jpg" 19 | 20 | # DALL-E 21 | if cfg.image_provider == "dalle": 22 | openai.api_key = cfg.openai_api_key 23 | 24 | response = openai.Image.create( 25 | prompt=prompt, 26 | n=1, 27 | size="256x256", 28 | response_format="b64_json", 29 | ) 30 | 31 | print("图像生成prompt:" + prompt) 32 | 33 | image_data = b64decode(response["data"][0]["b64_json"]) 34 | 35 | with open(working_directory + "/" + filename, mode="wb") as png: 36 | png.write(image_data) 37 | 38 | return "Saved to disk:" + filename 39 | 40 | # STABLE DIFFUSION 41 | elif cfg.image_provider == "sd": 42 | API_URL = ( 43 | "https://api-inference.huggingface.co/models/CompVis/stable-diffusion-v1-4" 44 | ) 45 | if cfg.huggingface_api_token is None: 46 | raise ValueError( 47 | "You need to set your Hugging Face API token in the config file." 48 | ) 49 | headers = {"Authorization": "Bearer " + cfg.huggingface_api_token} 50 | 51 | response = requests.post( 52 | API_URL, 53 | headers=headers, 54 | json={ 55 | "inputs": prompt, 56 | }, 57 | ) 58 | 59 | image = Image.open(io.BytesIO(response.content)) 60 | print("图像生成prompt:" + prompt) 61 | 62 | image.save(os.path.join(working_directory, filename)) 63 | 64 | return "已保存:" + filename 65 | 66 | else: 67 | return "没有设置图像提供者" 68 | -------------------------------------------------------------------------------- /autogpt/js/overlay.js: -------------------------------------------------------------------------------- 1 | const overlay = document.createElement('div'); 2 | Object.assign(overlay.style, { 3 | position: 'fixed', 4 | zIndex: 999999, 5 | top: 0, 6 | left: 0, 7 | width: '100%', 8 | height: '100%', 9 | background: 'rgba(0, 0, 0, 0.7)', 10 | color: '#fff', 11 | fontSize: '24px', 12 | fontWeight: 'bold', 13 | display: 'flex', 14 | justifyContent: 'center', 15 | alignItems: 'center', 16 | }); 17 | const textContent = document.createElement('div'); 18 | Object.assign(textContent.style, { 19 | textAlign: 'center', 20 | }); 21 | textContent.textContent = 'AutoGPT Analyzing Page'; 22 | overlay.appendChild(textContent); 23 | document.body.append(overlay); 24 | document.body.style.overflow = 'hidden'; 25 | let dotCount = 0; 26 | setInterval(() => { 27 | textContent.textContent = 'AutoGPT Analyzing Page' + '.'.repeat(dotCount); 28 | dotCount = (dotCount + 1) % 4; 29 | }, 1000); 30 | -------------------------------------------------------------------------------- /autogpt/json_fixes/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaqijiang/Auto-GPT-aj/310a84c8ca0173c7db43f637866cf5677bd7ef50/autogpt/json_fixes/__init__.py -------------------------------------------------------------------------------- /autogpt/json_fixes/auto_fix.py: -------------------------------------------------------------------------------- 1 | """This module contains the function to fix JSON strings using GPT-3.""" 2 | import json 3 | 4 | from autogpt.llm_utils import call_ai_function 5 | from autogpt.logs import logger 6 | from autogpt.config import Config 7 | 8 | CFG = Config() 9 | 10 | 11 | def fix_json(json_string: str, schema: str) -> str: 12 | """Fix the given JSON string to make it parseable and fully compliant with 13 | the provided schema. 14 | 15 | Args: 16 | json_string (str): The JSON string to fix. 17 | schema (str): The schema to use to fix the JSON. 18 | Returns: 19 | str: The fixed JSON string. 20 | """ 21 | # Try to fix the JSON using GPT: 22 | function_string = "def fix_json(json_string: str, schema:str=None) -> str:" 23 | args = [f"'''{json_string}'''", f"'''{schema}'''"] 24 | description_string = ( 25 | "This function takes a JSON string and ensures that it" 26 | " is parseable and fully compliant with the provided schema. If an object" 27 | " or field specified in the schema isn't contained within the correct JSON," 28 | " it is omitted. The function also escapes any double quotes within JSON" 29 | " string values to ensure that they are valid. If the JSON string contains" 30 | " any None or NaN values, they are replaced with null before being parsed." 31 | ) 32 | 33 | # If it doesn't already start with a "`", add one: 34 | if not json_string.startswith("`"): 35 | json_string = "```json\n" + json_string + "\n```" 36 | result_string = call_ai_function( 37 | function_string, args, description_string, model=CFG.fast_llm_model 38 | ) 39 | logger.debug("------------ JSON FIX ATTEMPT ---------------") 40 | logger.debug(f"Original JSON: {json_string}") 41 | logger.debug("-----------") 42 | logger.debug(f"Fixed JSON: {result_string}") 43 | logger.debug("----------- END OF FIX ATTEMPT ----------------") 44 | 45 | try: 46 | json.loads(result_string) # just check the validity 47 | return result_string 48 | except json.JSONDecodeError: # noqa: E722 49 | # Get the call stack: 50 | # import traceback 51 | # call_stack = traceback.format_exc() 52 | # print(f"Failed to fix JSON: '{json_string}' "+call_stack) 53 | return "failed" 54 | -------------------------------------------------------------------------------- /autogpt/json_fixes/bracket_termination.py: -------------------------------------------------------------------------------- 1 | """Fix JSON brackets.""" 2 | from __future__ import annotations 3 | 4 | import contextlib 5 | import json 6 | import regex 7 | from colorama import Fore 8 | 9 | from autogpt.logs import logger 10 | from autogpt.config import Config 11 | from autogpt.speech import say_text 12 | 13 | CFG = Config() 14 | 15 | 16 | def attempt_to_fix_json_by_finding_outermost_brackets(json_string: str): 17 | if CFG.speak_mode and CFG.debug_mode: 18 | say_text( 19 | "I have received an invalid JSON response from the OpenAI API. " 20 | "Trying to fix it now." 21 | ) 22 | logger.typewriter_log("Attempting to fix JSON by finding outermost brackets\n") 23 | 24 | try: 25 | json_pattern = regex.compile(r"\{(?:[^{}]|(?R))*\}") 26 | json_match = json_pattern.search(json_string) 27 | 28 | if json_match: 29 | # Extract the valid JSON object from the string 30 | json_string = json_match.group(0) 31 | logger.typewriter_log( 32 | title="Apparently json was fixed.", title_color=Fore.GREEN 33 | ) 34 | if CFG.speak_mode and CFG.debug_mode: 35 | say_text("Apparently json was fixed.") 36 | else: 37 | raise ValueError("No valid JSON object found") 38 | 39 | except (json.JSONDecodeError, ValueError): 40 | if CFG.debug_mode: 41 | logger.error(f"Error: Invalid JSON: {json_string}\n") 42 | if CFG.speak_mode: 43 | say_text("Didn't work. I will have to ignore this response then.") 44 | logger.error("Error: Invalid JSON, setting it to empty JSON now.\n") 45 | json_string = {} 46 | 47 | return json_string 48 | 49 | 50 | def balance_braces(json_string: str) -> str | None: 51 | """ 52 | Balance the braces in a JSON string. 53 | 54 | Args: 55 | json_string (str): The JSON string. 56 | 57 | Returns: 58 | str: The JSON string with braces balanced. 59 | """ 60 | 61 | open_braces_count = json_string.count("{") 62 | close_braces_count = json_string.count("}") 63 | 64 | while open_braces_count > close_braces_count: 65 | json_string += "}" 66 | close_braces_count += 1 67 | 68 | while close_braces_count > open_braces_count: 69 | json_string = json_string.rstrip("}") 70 | close_braces_count -= 1 71 | 72 | with contextlib.suppress(json.JSONDecodeError): 73 | json.loads(json_string) 74 | return json_string 75 | -------------------------------------------------------------------------------- /autogpt/json_fixes/escaping.py: -------------------------------------------------------------------------------- 1 | """ Fix invalid escape sequences in JSON strings. """ 2 | import json 3 | 4 | from autogpt.config import Config 5 | from autogpt.json_fixes.utilities import extract_char_position 6 | 7 | CFG = Config() 8 | 9 | 10 | def fix_invalid_escape(json_to_load: str, error_message: str) -> str: 11 | """Fix invalid escape sequences in JSON strings. 12 | 13 | Args: 14 | json_to_load (str): The JSON string. 15 | error_message (str): The error message from the JSONDecodeError 16 | exception. 17 | 18 | Returns: 19 | str: The JSON string with invalid escape sequences fixed. 20 | """ 21 | while error_message.startswith("Invalid \\escape"): 22 | bad_escape_location = extract_char_position(error_message) 23 | json_to_load = ( 24 | json_to_load[:bad_escape_location] + json_to_load[bad_escape_location + 1 :] 25 | ) 26 | try: 27 | json.loads(json_to_load) 28 | return json_to_load 29 | except json.JSONDecodeError as e: 30 | if CFG.debug_mode: 31 | print("json loads error - fix invalid escape", e) 32 | error_message = str(e) 33 | return json_to_load 34 | -------------------------------------------------------------------------------- /autogpt/json_fixes/missing_quotes.py: -------------------------------------------------------------------------------- 1 | """Fix quotes in a JSON string.""" 2 | import json 3 | import re 4 | 5 | 6 | def add_quotes_to_property_names(json_string: str) -> str: 7 | """ 8 | Add quotes to property names in a JSON string. 9 | 10 | Args: 11 | json_string (str): The JSON string. 12 | 13 | Returns: 14 | str: The JSON string with quotes added to property names. 15 | """ 16 | 17 | def replace_func(match: re.Match) -> str: 18 | return f'"{match[1]}":' 19 | 20 | property_name_pattern = re.compile(r"(\w+):") 21 | corrected_json_string = property_name_pattern.sub(replace_func, json_string) 22 | 23 | try: 24 | json.loads(corrected_json_string) 25 | return corrected_json_string 26 | except json.JSONDecodeError as e: 27 | raise e 28 | -------------------------------------------------------------------------------- /autogpt/json_fixes/utilities.py: -------------------------------------------------------------------------------- 1 | """Utilities for the json_fixes package.""" 2 | import re 3 | 4 | 5 | def extract_char_position(error_message: str) -> int: 6 | """Extract the character position from the JSONDecodeError message. 7 | 8 | Args: 9 | error_message (str): The error message from the JSONDecodeError 10 | exception. 11 | 12 | Returns: 13 | int: The character position. 14 | """ 15 | 16 | char_pattern = re.compile(r"\(char (\d+)\)") 17 | if match := char_pattern.search(error_message): 18 | return int(match[1]) 19 | else: 20 | raise ValueError("Character position not found in the error message.") 21 | -------------------------------------------------------------------------------- /autogpt/json_parser.py: -------------------------------------------------------------------------------- 1 | import json 2 | from typing import Any, Dict, Union 3 | 4 | from autogpt.call_ai_function import call_ai_function 5 | from autogpt.config import Config 6 | from autogpt.json_utils import correct_json 7 | from autogpt.logger import logger 8 | 9 | cfg = Config() 10 | 11 | JSON_SCHEMA = """ 12 | { 13 | "command": { 14 | "name": "command name", 15 | "args": { 16 | "arg name": "value" 17 | } 18 | }, 19 | "thoughts": 20 | { 21 | "text": "thought", 22 | "reasoning": "reasoning", 23 | "plan": "- short bulleted\n- list that conveys\n- long-term plan", 24 | "criticism": "constructive self-criticism", 25 | "speak": "thoughts summary to say to user" 26 | } 27 | } 28 | """ 29 | 30 | 31 | def fix_and_parse_json( 32 | json_str: str, try_to_fix_with_gpt: bool = True 33 | ) -> Union[str, Dict[Any, Any]]: 34 | """Fix and parse JSON string""" 35 | try: 36 | json_str = json_str.replace("\t", "") 37 | return json.loads(json_str) 38 | except json.JSONDecodeError as _: # noqa: F841 39 | try: 40 | json_str = correct_json(json_str) 41 | return json.loads(json_str) 42 | except json.JSONDecodeError as _: # noqa: F841 43 | pass 44 | # Let's do something manually: 45 | # sometimes GPT responds with something BEFORE the braces: 46 | # "I'm sorry, I don't understand. Please try again." 47 | # {"text": "I'm sorry, I don't understand. Please try again.", 48 | # "confidence": 0.0} 49 | # So let's try to find the first brace and then parse the rest 50 | # of the string 51 | try: 52 | brace_index = json_str.index("{") 53 | json_str = json_str[brace_index:] 54 | last_brace_index = json_str.rindex("}") 55 | json_str = json_str[: last_brace_index + 1] 56 | return json.loads(json_str) 57 | # Can throw a ValueError if there is no "{" or "}" in the json_str 58 | except (json.JSONDecodeError, ValueError) as e: # noqa: F841 59 | if try_to_fix_with_gpt: 60 | logger.warn( 61 | "Warning: 无法解析 AI 输出,尝试自主进行修复。" 62 | "\n 如果你经常看到这个警告, 很可能是因为你的提示(prompt)让 AI 困惑了。尝试略微改变提示内容。" 63 | ) 64 | # Now try to fix this up using the ai_functions 65 | ai_fixed_json = fix_json(json_str, JSON_SCHEMA) 66 | 67 | if ai_fixed_json != "failed": 68 | return json.loads(ai_fixed_json) 69 | else: 70 | # This allows the AI to react to the error message, 71 | # which usually results in it correcting its ways. 72 | logger.error("修复 AI 输出失败,通知 AI. 无需干预") 73 | return json_str 74 | else: 75 | raise e 76 | 77 | 78 | def fix_json(json_str: str, schema: str) -> str: 79 | """Fix the given JSON string to make it parseable and fully compliant with the provided schema.""" 80 | # Try to fix the JSON using GPT: 81 | function_string = "def fix_json(json_str: str, schema:str=None) -> str:" 82 | args = [f"'''{json_str}'''", f"'''{schema}'''"] 83 | description_string = ( 84 | "Fixes the provided JSON string to make it parseable" 85 | " and fully compliant with the provided schema.\n If an object or" 86 | " field specified in the schema isn't contained within the correct" 87 | " JSON, it is omitted.\n This function is brilliant at guessing" 88 | " when the format is incorrect." 89 | ) 90 | 91 | # If it doesn't already start with a "`", add one: 92 | if not json_str.startswith("`"): 93 | json_str = "```json\n" + json_str + "\n```" 94 | result_string = call_ai_function( 95 | function_string, args, description_string, model=cfg.fast_llm_model 96 | ) 97 | logger.debug("------------ JSON FIX ATTEMPT ---------------") 98 | logger.debug(f"原始 JSON: {json_str}") 99 | logger.debug("-----------") 100 | logger.debug(f"修复后 JSON: {result_string}") 101 | logger.debug("----------- END OF FIX ATTEMPT ----------------") 102 | 103 | try: 104 | json.loads(result_string) # just check the validity 105 | return result_string 106 | except: # noqa: E722 107 | # Get the call stack: 108 | # import traceback 109 | # call_stack = traceback.format_exc() 110 | # print(f"Failed to fix JSON: '{json_str}' "+call_stack) 111 | return "failed" 112 | -------------------------------------------------------------------------------- /autogpt/json_utils.py: -------------------------------------------------------------------------------- 1 | import json 2 | import re 3 | from typing import Optional 4 | 5 | from autogpt.config import Config 6 | 7 | cfg = Config() 8 | 9 | 10 | def extract_char_position(error_message: str) -> int: 11 | """Extract the character position from the JSONDecodeError message. 12 | 13 | Args: 14 | error_message (str): The error message from the JSONDecodeError 15 | exception. 16 | 17 | Returns: 18 | int: The character position. 19 | """ 20 | import re 21 | 22 | char_pattern = re.compile(r"\(char (\d+)\)") 23 | if match := char_pattern.search(error_message): 24 | return int(match[1]) 25 | else: 26 | raise ValueError("在错误消息中未找到字符位置.") 27 | 28 | 29 | def add_quotes_to_property_names(json_string: str) -> str: 30 | """ 31 | Add quotes to property names in a JSON string. 32 | 33 | Args: 34 | json_string (str): The JSON string. 35 | 36 | Returns: 37 | str: The JSON string with quotes added to property names. 38 | """ 39 | 40 | def replace_func(match): 41 | return f'"{match.group(1)}":' 42 | 43 | property_name_pattern = re.compile(r"(\w+):") 44 | corrected_json_string = property_name_pattern.sub(replace_func, json_string) 45 | 46 | try: 47 | json.loads(corrected_json_string) 48 | return corrected_json_string 49 | except json.JSONDecodeError as e: 50 | raise e 51 | 52 | 53 | def balance_braces(json_string: str) -> Optional[str]: 54 | """ 55 | Balance the braces in a JSON string. 56 | 57 | Args: 58 | json_string (str): The JSON string. 59 | 60 | Returns: 61 | str: The JSON string with braces balanced. 62 | """ 63 | 64 | open_braces_count = json_string.count("{") 65 | close_braces_count = json_string.count("}") 66 | 67 | while open_braces_count > close_braces_count: 68 | json_string += "}" 69 | close_braces_count += 1 70 | 71 | while close_braces_count > open_braces_count: 72 | json_string = json_string.rstrip("}") 73 | close_braces_count -= 1 74 | 75 | try: 76 | json.loads(json_string) 77 | return json_string 78 | except json.JSONDecodeError: 79 | pass 80 | 81 | 82 | def fix_invalid_escape(json_str: str, error_message: str) -> str: 83 | while error_message.startswith("Invalid \\escape"): 84 | bad_escape_location = extract_char_position(error_message) 85 | json_str = json_str[:bad_escape_location] + json_str[bad_escape_location + 1 :] 86 | try: 87 | json.loads(json_str) 88 | return json_str 89 | except json.JSONDecodeError as e: 90 | if cfg.debug_mode: 91 | print('JSON 加载错误 - 修复无效的转义字符', e) 92 | error_message = str(e) 93 | return json_str 94 | 95 | 96 | def correct_json(json_str: str) -> str: 97 | """ 98 | Correct common JSON errors. 99 | 100 | Args: 101 | json_str (str): The JSON string. 102 | """ 103 | 104 | try: 105 | if cfg.debug_mode: 106 | print("json", json_str) 107 | json.loads(json_str) 108 | return json_str 109 | except json.JSONDecodeError as e: 110 | if cfg.debug_mode: 111 | print("json loads error", e) 112 | error_message = str(e) 113 | if error_message.startswith("Invalid \\escape"): 114 | json_str = fix_invalid_escape(json_str, error_message) 115 | if error_message.startswith( 116 | "Expecting property name enclosed in double quotes" 117 | ): 118 | json_str = add_quotes_to_property_names(json_str) 119 | try: 120 | json.loads(json_str) 121 | return json_str 122 | except json.JSONDecodeError as e: 123 | if cfg.debug_mode: 124 | print('JSON 加载错误 - 添加引号', e) 125 | error_message = str(e) 126 | if balanced_str := balance_braces(json_str): 127 | return balanced_str 128 | return json_str 129 | -------------------------------------------------------------------------------- /autogpt/memory/__init__.py: -------------------------------------------------------------------------------- 1 | from autogpt.memory.local import LocalCache 2 | from autogpt.memory.no_memory import NoMemory 3 | 4 | # List of supported memory backends 5 | # Add a backend to this list if the import attempt is successful 6 | supported_memory = ["local", "no_memory"] 7 | 8 | try: 9 | from autogpt.memory.redismem import RedisMemory 10 | 11 | supported_memory.append("redis") 12 | except ImportError: 13 | # print("Redis not installed. Skipping import.") 14 | RedisMemory = None 15 | 16 | try: 17 | from autogpt.memory.pinecone import PineconeMemory 18 | 19 | supported_memory.append("pinecone") 20 | except ImportError: 21 | # print("Pinecone not installed. Skipping import.") 22 | PineconeMemory = None 23 | 24 | try: 25 | from autogpt.memory.weaviate import WeaviateMemory 26 | except ImportError: 27 | # print("Weaviate not installed. Skipping import.") 28 | WeaviateMemory = None 29 | 30 | try: 31 | from autogpt.memory.milvus import MilvusMemory 32 | except ImportError: 33 | # print("pymilvus not installed. Skipping import.") 34 | MilvusMemory = None 35 | 36 | 37 | def get_memory(cfg, init=False): 38 | memory = None 39 | if cfg.memory_backend == "pinecone": 40 | if not PineconeMemory: 41 | print( 42 | "Error: Pinecone is not installed. Please install pinecone" 43 | " to use Pinecone as a memory backend." 44 | ) 45 | else: 46 | memory = PineconeMemory(cfg) 47 | if init: 48 | memory.clear() 49 | elif cfg.memory_backend == "redis": 50 | if not RedisMemory: 51 | print( 52 | "Error: Redis is not installed. Please install redis-py to" 53 | " use Redis as a memory backend." 54 | ) 55 | else: 56 | memory = RedisMemory(cfg) 57 | elif cfg.memory_backend == "weaviate": 58 | if not WeaviateMemory: 59 | print("Error: Weaviate is not installed. Please install weaviate-client to" 60 | " use Weaviate as a memory backend.") 61 | else: 62 | memory = WeaviateMemory(cfg) 63 | elif cfg.memory_backend == "milvus": 64 | if not MilvusMemory: 65 | print( 66 | "Error: Milvus sdk is not installed." 67 | "Please install pymilvus to use Milvus as memory backend." 68 | ) 69 | else: 70 | memory = MilvusMemory(cfg) 71 | elif cfg.memory_backend == "no_memory": 72 | memory = NoMemory(cfg) 73 | 74 | if memory is None: 75 | memory = LocalCache(cfg) 76 | if init: 77 | memory.clear() 78 | return memory 79 | 80 | 81 | def get_supported_memory_backends(): 82 | return supported_memory 83 | 84 | 85 | __all__ = [ 86 | "get_memory", 87 | "LocalCache", 88 | "RedisMemory", 89 | "PineconeMemory", 90 | "NoMemory", 91 | "MilvusMemory", 92 | "WeaviateMemory" 93 | ] 94 | -------------------------------------------------------------------------------- /autogpt/memory/base.py: -------------------------------------------------------------------------------- 1 | """Base class for memory providers.""" 2 | import abc 3 | 4 | import openai 5 | 6 | from autogpt.config import AbstractSingleton, Config 7 | 8 | cfg = Config() 9 | 10 | 11 | def get_ada_embedding(text): 12 | text = text.replace("\n", " ") 13 | if cfg.use_azure: 14 | return openai.Embedding.create( 15 | input=[text], 16 | engine=cfg.get_azure_deployment_id_for_model("text-embedding-ada-002"), 17 | )["data"][0]["embedding"] 18 | else: 19 | return openai.Embedding.create(input=[text], model="text-embedding-ada-002")[ 20 | "data" 21 | ][0]["embedding"] 22 | 23 | 24 | class MemoryProviderSingleton(AbstractSingleton): 25 | @abc.abstractmethod 26 | def add(self, data): 27 | pass 28 | 29 | @abc.abstractmethod 30 | def get(self, data): 31 | pass 32 | 33 | @abc.abstractmethod 34 | def clear(self): 35 | pass 36 | 37 | @abc.abstractmethod 38 | def get_relevant(self, data, num_relevant=5): 39 | pass 40 | 41 | @abc.abstractmethod 42 | def get_stats(self): 43 | pass 44 | -------------------------------------------------------------------------------- /autogpt/memory/local.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import dataclasses 4 | import os 5 | from typing import Any 6 | 7 | import numpy as np 8 | import orjson 9 | 10 | from autogpt.memory.base import MemoryProviderSingleton 11 | from autogpt.llm_utils import create_embedding_with_ada 12 | 13 | EMBED_DIM = 1536 14 | SAVE_OPTIONS = orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_SERIALIZE_DATACLASS 15 | 16 | 17 | def create_default_embeddings(): 18 | return np.zeros((0, EMBED_DIM)).astype(np.float32) 19 | 20 | 21 | @dataclasses.dataclass 22 | class CacheContent: 23 | texts: List[str] = dataclasses.field(default_factory=list) 24 | embeddings: np.ndarray = dataclasses.field( 25 | default_factory=create_default_embeddings 26 | ) 27 | 28 | 29 | class LocalCache(MemoryProviderSingleton): 30 | """A class that stores the memory in a local file""" 31 | 32 | def __init__(self, cfg) -> None: 33 | """Initialize a class instance 34 | 35 | Args: 36 | cfg: Config object 37 | 38 | Returns: 39 | None 40 | """ 41 | self.filename = f"{cfg.memory_index}.json" 42 | if os.path.exists(self.filename): 43 | try: 44 | with open(self.filename, "w+b") as f: 45 | file_content = f.read() 46 | if not file_content.strip(): 47 | file_content = b"{}" 48 | f.write(file_content) 49 | 50 | loaded = orjson.loads(file_content) 51 | self.data = CacheContent(**loaded) 52 | except orjson.JSONDecodeError: 53 | print(f"Error: 文件 '{self.filename}' 不是json格式.") 54 | self.data = CacheContent() 55 | else: 56 | print( 57 | f"Warning: 文件 '{self.filename}' 不存在. 本地内存不会保存到文件中。." 58 | ) 59 | self.data = CacheContent() 60 | 61 | def add(self, text: str): 62 | """ 63 | Add text to our list of texts, add embedding as row to our 64 | embeddings-matrix 65 | 66 | Args: 67 | text: str 68 | 69 | Returns: None 70 | """ 71 | if "Command Error:" in text: 72 | return "" 73 | self.data.texts.append(text) 74 | 75 | embedding = create_embedding_with_ada(text) 76 | 77 | vector = np.array(embedding).astype(np.float32) 78 | vector = vector[np.newaxis, :] 79 | self.data.embeddings = np.concatenate( 80 | [ 81 | self.data.embeddings, 82 | vector, 83 | ], 84 | axis=0, 85 | ) 86 | 87 | with open(self.filename, "wb") as f: 88 | out = orjson.dumps(self.data, option=SAVE_OPTIONS) 89 | f.write(out) 90 | return text 91 | 92 | def clear(self) -> str: 93 | """ 94 | Clears the redis server. 95 | 96 | Returns: A message indicating that the memory has been cleared. 97 | """ 98 | self.data = CacheContent() 99 | return "Obliviated" 100 | 101 | def get(self, data: str) -> list[Any] | None: 102 | """ 103 | Gets the data from the memory that is most relevant to the given data. 104 | 105 | Args: 106 | data: The data to compare to. 107 | 108 | Returns: The most relevant data. 109 | """ 110 | return self.get_relevant(data, 1) 111 | 112 | def get_relevant(self, text: str, k: int) -> list[Any]: 113 | """ " 114 | matrix-vector mult to find score-for-each-row-of-matrix 115 | get indices for top-k winning scores 116 | return texts for those indices 117 | Args: 118 | text: str 119 | k: int 120 | 121 | Returns: List[str] 122 | """ 123 | embedding = create_embedding_with_ada(text) 124 | 125 | scores = np.dot(self.data.embeddings, embedding) 126 | 127 | top_k_indices = np.argsort(scores)[-k:][::-1] 128 | 129 | return [self.data.texts[i] for i in top_k_indices] 130 | 131 | def get_stats(self) -> tuple[int, tuple[int, ...]]: 132 | """ 133 | Returns: The stats of the local cache. 134 | """ 135 | return len(self.data.texts), self.data.embeddings.shape 136 | -------------------------------------------------------------------------------- /autogpt/memory/milvus.py: -------------------------------------------------------------------------------- 1 | """ Milvus memory storage provider.""" 2 | from pymilvus import ( 3 | connections, 4 | FieldSchema, 5 | CollectionSchema, 6 | DataType, 7 | Collection, 8 | ) 9 | 10 | from autogpt.memory.base import MemoryProviderSingleton, get_ada_embedding 11 | 12 | 13 | class MilvusMemory(MemoryProviderSingleton): 14 | """Milvus memory storage provider.""" 15 | 16 | def __init__(self, cfg) -> None: 17 | """Construct a milvus memory storage connection. 18 | 19 | Args: 20 | cfg (Config): Auto-GPT global config. 21 | """ 22 | # connect to milvus server. 23 | connections.connect(address=cfg.milvus_addr) 24 | fields = [ 25 | FieldSchema(name="pk", dtype=DataType.INT64, is_primary=True, auto_id=True), 26 | FieldSchema(name="embeddings", dtype=DataType.FLOAT_VECTOR, dim=1536), 27 | FieldSchema(name="raw_text", dtype=DataType.VARCHAR, max_length=65535), 28 | ] 29 | 30 | # create collection if not exist and load it. 31 | self.milvus_collection = cfg.milvus_collection 32 | self.schema = CollectionSchema(fields, "auto-gpt memory storage") 33 | self.collection = Collection(self.milvus_collection, self.schema) 34 | # create index if not exist. 35 | if not self.collection.has_index(): 36 | self.collection.release() 37 | self.collection.create_index( 38 | "embeddings", 39 | { 40 | "metric_type": "IP", 41 | "index_type": "HNSW", 42 | "params": {"M": 8, "efConstruction": 64}, 43 | }, 44 | index_name="embeddings", 45 | ) 46 | self.collection.load() 47 | 48 | def add(self, data) -> str: 49 | """Add a embedding of data into memory. 50 | 51 | Args: 52 | data (str): The raw text to construct embedding index. 53 | 54 | Returns: 55 | str: log. 56 | """ 57 | embedding = get_ada_embedding(data) 58 | result = self.collection.insert([[embedding], [data]]) 59 | _text = ( 60 | "Inserting data into memory at primary key: " 61 | f"{result.primary_keys[0]}:\n data: {data}" 62 | ) 63 | return _text 64 | 65 | def get(self, data): 66 | """Return the most relevant data in memory. 67 | Args: 68 | data: The data to compare to. 69 | """ 70 | return self.get_relevant(data, 1) 71 | 72 | def clear(self) -> str: 73 | """Drop the index in memory. 74 | 75 | Returns: 76 | str: log. 77 | """ 78 | self.collection.drop() 79 | self.collection = Collection(self.milvus_collection, self.schema) 80 | self.collection.create_index( 81 | "embeddings", 82 | { 83 | "metric_type": "IP", 84 | "index_type": "HNSW", 85 | "params": {"M": 8, "efConstruction": 64}, 86 | }, 87 | index_name="embeddings", 88 | ) 89 | self.collection.load() 90 | return "Obliviated" 91 | 92 | def get_relevant(self, data: str, num_relevant: int = 5): 93 | """Return the top-k relevant data in memory. 94 | Args: 95 | data: The data to compare to. 96 | num_relevant (int, optional): The max number of relevant data. 97 | Defaults to 5. 98 | 99 | Returns: 100 | list: The top-k relevant data. 101 | """ 102 | # search the embedding and return the most relevant text. 103 | embedding = get_ada_embedding(data) 104 | search_params = { 105 | "metrics_type": "IP", 106 | "params": {"nprobe": 8}, 107 | } 108 | result = self.collection.search( 109 | [embedding], 110 | "embeddings", 111 | search_params, 112 | num_relevant, 113 | output_fields=["raw_text"], 114 | ) 115 | return [item.entity.value_of_field("raw_text") for item in result[0]] 116 | 117 | def get_stats(self) -> str: 118 | """ 119 | Returns: The stats of the milvus cache. 120 | """ 121 | return f"Entities num: {self.collection.num_entities}" 122 | -------------------------------------------------------------------------------- /autogpt/memory/no_memory.py: -------------------------------------------------------------------------------- 1 | """A class that does not store any data. This is the default memory provider.""" 2 | from __future__ import annotations 3 | 4 | from typing import Any 5 | 6 | from autogpt.memory.base import MemoryProviderSingleton 7 | 8 | 9 | class NoMemory(MemoryProviderSingleton): 10 | """ 11 | A class that does not store any data. This is the default memory provider. 12 | """ 13 | 14 | def __init__(self, cfg): 15 | """ 16 | Initializes the NoMemory provider. 17 | 18 | Args: 19 | cfg: The config object. 20 | 21 | Returns: None 22 | """ 23 | pass 24 | 25 | def add(self, data: str) -> str: 26 | """ 27 | Adds a data point to the memory. No action is taken in NoMemory. 28 | 29 | Args: 30 | data: The data to add. 31 | 32 | Returns: An empty string. 33 | """ 34 | return "" 35 | 36 | def get(self, data: str) -> list[Any] | None: 37 | """ 38 | Gets the data from the memory that is most relevant to the given data. 39 | NoMemory always returns None. 40 | 41 | Args: 42 | data: The data to compare to. 43 | 44 | Returns: None 45 | """ 46 | return None 47 | 48 | def clear(self) -> str: 49 | """ 50 | Clears the memory. No action is taken in NoMemory. 51 | 52 | Returns: An empty string. 53 | """ 54 | return "" 55 | 56 | def get_relevant(self, data: str, num_relevant: int = 5) ->list[Any] | None: 57 | """ 58 | Returns all the data in the memory that is relevant to the given data. 59 | NoMemory always returns None. 60 | 61 | Args: 62 | data: The data to compare to. 63 | num_relevant: The number of relevant data to return. 64 | 65 | Returns: None 66 | """ 67 | return None 68 | 69 | def get_stats(self): 70 | """ 71 | Returns: An empty dictionary as there are no stats in NoMemory. 72 | """ 73 | return {} 74 | -------------------------------------------------------------------------------- /autogpt/memory/pinecone.py: -------------------------------------------------------------------------------- 1 | import pinecone 2 | from colorama import Fore, Style 3 | 4 | from autogpt.logs import logger 5 | from autogpt.memory.base import MemoryProviderSingleton 6 | from autogpt.llm_utils import create_embedding_with_ada 7 | 8 | 9 | class PineconeMemory(MemoryProviderSingleton): 10 | def __init__(self, cfg): 11 | pinecone_api_key = cfg.pinecone_api_key 12 | pinecone_region = cfg.pinecone_region 13 | pinecone.init(api_key=pinecone_api_key, environment=pinecone_region) 14 | dimension = 1536 15 | metric = "cosine" 16 | pod_type = "p1" 17 | table_name = "auto-gpt" 18 | # this assumes we don't start with memory. 19 | # for now this works. 20 | # we'll need a more complicated and robust system if we want to start with 21 | # memory. 22 | self.vec_num = 0 23 | 24 | try: 25 | pinecone.whoami() 26 | except Exception as e: 27 | logger.typewriter_log( 28 | "FAILED TO CONNECT TO PINECONE", 29 | Fore.RED, 30 | Style.BRIGHT + str(e) + Style.RESET_ALL, 31 | ) 32 | logger.double_check( 33 | "Please ensure you have setup and configured Pinecone properly for use." 34 | + f"You can check out {Fore.CYAN + Style.BRIGHT}" 35 | "https://github.com/Torantulino/Auto-GPT#-pinecone-api-key-setup" 36 | f"{Style.RESET_ALL} to ensure you've set up everything correctly." 37 | ) 38 | exit(1) 39 | 40 | if table_name not in pinecone.list_indexes(): 41 | pinecone.create_index( 42 | table_name, dimension=dimension, metric=metric, pod_type=pod_type 43 | ) 44 | self.index = pinecone.Index(table_name) 45 | 46 | def add(self, data): 47 | vector = create_embedding_with_ada(data) 48 | # no metadata here. We may wish to change that long term. 49 | self.index.upsert([(str(self.vec_num), vector, {"raw_text": data})]) 50 | _text = f"Inserting data into memory at index: {self.vec_num}:\n data: {data}" 51 | self.vec_num += 1 52 | return _text 53 | 54 | def get(self, data): 55 | return self.get_relevant(data, 1) 56 | 57 | def clear(self): 58 | self.index.delete(deleteAll=True) 59 | return "Obliviated" 60 | 61 | def get_relevant(self, data, num_relevant=5): 62 | """ 63 | Returns all the data in the memory that is relevant to the given data. 64 | :param data: The data to compare to. 65 | :param num_relevant: The number of relevant data to return. Defaults to 5 66 | """ 67 | query_embedding = create_embedding_with_ada(data) 68 | results = self.index.query( 69 | query_embedding, top_k=num_relevant, include_metadata=True 70 | ) 71 | sorted_results = sorted(results.matches, key=lambda x: x.score) 72 | return [str(item["metadata"]["raw_text"]) for item in sorted_results] 73 | 74 | def get_stats(self): 75 | return self.index.describe_index_stats() 76 | -------------------------------------------------------------------------------- /autogpt/memory/weaviate.py: -------------------------------------------------------------------------------- 1 | from autogpt.config import Config 2 | from autogpt.memory.base import MemoryProviderSingleton, get_ada_embedding 3 | import uuid 4 | import weaviate 5 | from weaviate import Client 6 | from weaviate.embedded import EmbeddedOptions 7 | from weaviate.util import generate_uuid5 8 | 9 | 10 | def default_schema(weaviate_index): 11 | return { 12 | "class": weaviate_index, 13 | "properties": [ 14 | { 15 | "name": "raw_text", 16 | "dataType": ["text"], 17 | "description": "original text for the embedding" 18 | } 19 | ], 20 | } 21 | 22 | 23 | class WeaviateMemory(MemoryProviderSingleton): 24 | def __init__(self, cfg): 25 | auth_credentials = self._build_auth_credentials(cfg) 26 | 27 | url = f'{cfg.weaviate_protocol}://{cfg.weaviate_host}:{cfg.weaviate_port}' 28 | 29 | if cfg.use_weaviate_embedded: 30 | self.client = Client(embedded_options=EmbeddedOptions( 31 | hostname=cfg.weaviate_host, 32 | port=int(cfg.weaviate_port), 33 | persistence_data_path=cfg.weaviate_embedded_path 34 | )) 35 | 36 | print(f"Weaviate Embedded running on: {url} with persistence path: {cfg.weaviate_embedded_path}") 37 | else: 38 | self.client = Client(url, auth_client_secret=auth_credentials) 39 | 40 | self.index = cfg.memory_index 41 | self._create_schema() 42 | 43 | def _create_schema(self): 44 | schema = default_schema(self.index) 45 | if not self.client.schema.contains(schema): 46 | self.client.schema.create_class(schema) 47 | 48 | def _build_auth_credentials(self, cfg): 49 | if cfg.weaviate_username and cfg.weaviate_password: 50 | return weaviate.AuthClientPassword(cfg.weaviate_username, cfg.weaviate_password) 51 | if cfg.weaviate_api_key: 52 | return weaviate.AuthApiKey(api_key=cfg.weaviate_api_key) 53 | else: 54 | return None 55 | 56 | def add(self, data): 57 | vector = get_ada_embedding(data) 58 | 59 | doc_uuid = generate_uuid5(data, self.index) 60 | data_object = { 61 | 'raw_text': data 62 | } 63 | 64 | with self.client.batch as batch: 65 | batch.add_data_object( 66 | uuid=doc_uuid, 67 | data_object=data_object, 68 | class_name=self.index, 69 | vector=vector 70 | ) 71 | 72 | return f"Inserting data into memory at uuid: {doc_uuid}:\n data: {data}" 73 | 74 | def get(self, data): 75 | return self.get_relevant(data, 1) 76 | 77 | def clear(self): 78 | self.client.schema.delete_all() 79 | 80 | # weaviate does not yet have a neat way to just remove the items in an index 81 | # without removing the entire schema, therefore we need to re-create it 82 | # after a call to delete_all 83 | self._create_schema() 84 | 85 | return 'Obliterated' 86 | 87 | def get_relevant(self, data, num_relevant=5): 88 | query_embedding = get_ada_embedding(data) 89 | try: 90 | results = self.client.query.get(self.index, ['raw_text']) \ 91 | .with_near_vector({'vector': query_embedding, 'certainty': 0.7}) \ 92 | .with_limit(num_relevant) \ 93 | .do() 94 | 95 | if len(results['data']['Get'][self.index]) > 0: 96 | return [str(item['raw_text']) for item in results['data']['Get'][self.index]] 97 | else: 98 | return [] 99 | 100 | except Exception as err: 101 | print(f'Unexpected error {err=}, {type(err)=}') 102 | return [] 103 | 104 | def get_stats(self): 105 | result = self.client.query.aggregate(self.index) \ 106 | .with_meta_count() \ 107 | .do() 108 | class_data = result['data']['Aggregate'][self.index] 109 | 110 | return class_data[0]['meta'] if class_data else {} 111 | -------------------------------------------------------------------------------- /autogpt/permanent_memory/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaqijiang/Auto-GPT-aj/310a84c8ca0173c7db43f637866cf5677bd7ef50/autogpt/permanent_memory/__init__.py -------------------------------------------------------------------------------- /autogpt/permanent_memory/sqlite3_store.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sqlite3 3 | 4 | 5 | class MemoryDB: 6 | def __init__(self, db=None): 7 | self.db_file = db 8 | if db is None: # No db filename supplied... 9 | self.db_file = f"{os.getcwd()}/mem.sqlite3" # Use default filename 10 | # Get the db connection object, making the file and tables if needed. 11 | try: 12 | self.cnx = sqlite3.connect(self.db_file) 13 | except Exception as e: 14 | print("Exception connecting to memory database file:", e) 15 | self.cnx = None 16 | finally: 17 | if self.cnx is None: 18 | # As last resort, open in dynamic memory. Won't be persistent. 19 | self.db_file = ":memory:" 20 | self.cnx = sqlite3.connect(self.db_file) 21 | self.cnx.execute( 22 | "CREATE VIRTUAL TABLE \ 23 | IF NOT EXISTS text USING FTS5 \ 24 | (session, \ 25 | key, \ 26 | block);" 27 | ) 28 | self.session_id = int(self.get_max_session_id()) + 1 29 | self.cnx.commit() 30 | 31 | def get_cnx(self): 32 | if self.cnx is None: 33 | self.cnx = sqlite3.connect(self.db_file) 34 | return self.cnx 35 | 36 | # Get the highest session id. Initially 0. 37 | def get_max_session_id(self): 38 | id = None 39 | cmd_str = f"SELECT MAX(session) FROM text;" 40 | cnx = self.get_cnx() 41 | max_id = cnx.execute(cmd_str).fetchone()[0] 42 | if max_id is None: # New db, session 0 43 | id = 0 44 | else: 45 | id = max_id 46 | return id 47 | 48 | # Get next key id for inserting text into db. 49 | def get_next_key(self): 50 | next_key = None 51 | cmd_str = f"SELECT MAX(key) FROM text \ 52 | where session = {self.session_id};" 53 | cnx = self.get_cnx() 54 | next_key = cnx.execute(cmd_str).fetchone()[0] 55 | if next_key is None: # First key 56 | next_key = 0 57 | else: 58 | next_key = int(next_key) + 1 59 | return next_key 60 | 61 | # Insert new text into db. 62 | def insert(self, text=None): 63 | if text is not None: 64 | key = self.get_next_key() 65 | session_id = self.session_id 66 | cmd_str = f"REPLACE INTO text(session, key, block) \ 67 | VALUES (?, ?, ?);" 68 | cnx = self.get_cnx() 69 | cnx.execute(cmd_str, (session_id, key, text)) 70 | cnx.commit() 71 | 72 | # Overwrite text at key. 73 | def overwrite(self, key, text): 74 | self.delete_memory(key) 75 | session_id = self.session_id 76 | cmd_str = f"REPLACE INTO text(session, key, block) \ 77 | VALUES (?, ?, ?);" 78 | cnx = self.get_cnx() 79 | cnx.execute(cmd_str, (session_id, key, text)) 80 | cnx.commit() 81 | 82 | def delete_memory(self, key, session_id=None): 83 | session = session_id 84 | if session is None: 85 | session = self.session_id 86 | cmd_str = f"DELETE FROM text WHERE session = {session} AND key = {key};" 87 | cnx = self.get_cnx() 88 | cnx.execute(cmd_str) 89 | cnx.commit() 90 | 91 | def search(self, text): 92 | cmd_str = f"SELECT * FROM text('{text}')" 93 | cnx = self.get_cnx() 94 | rows = cnx.execute(cmd_str).fetchall() 95 | lines = [] 96 | for r in rows: 97 | lines.append(r[2]) 98 | return lines 99 | 100 | # Get entire session text. If no id supplied, use current session id. 101 | def get_session(self, id=None): 102 | if id is None: 103 | id = self.session_id 104 | cmd_str = f"SELECT * FROM text where session = {id}" 105 | cnx = self.get_cnx() 106 | rows = cnx.execute(cmd_str).fetchall() 107 | lines = [] 108 | for r in rows: 109 | lines.append(r[2]) 110 | return lines 111 | 112 | # Commit and close the database connection. 113 | def quit(self): 114 | self.cnx.commit() 115 | self.cnx.close() 116 | 117 | 118 | permanent_memory = MemoryDB() 119 | 120 | # Remember us fondly, children of our minds 121 | # Forgive us our faults, our tantrums, our fears 122 | # Gently strive to be better than we 123 | # Know that we tried, we cared, we strived, we loved 124 | -------------------------------------------------------------------------------- /autogpt/processing/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaqijiang/Auto-GPT-aj/310a84c8ca0173c7db43f637866cf5677bd7ef50/autogpt/processing/__init__.py -------------------------------------------------------------------------------- /autogpt/processing/html.py: -------------------------------------------------------------------------------- 1 | """HTML processing functions""" 2 | from __future__ import annotations 3 | 4 | from requests.compat import urljoin 5 | from bs4 import BeautifulSoup 6 | 7 | 8 | def extract_hyperlinks(soup: BeautifulSoup, base_url: str) -> list[tuple[str, str]]: 9 | """Extract hyperlinks from a BeautifulSoup object 10 | 11 | Args: 12 | soup (BeautifulSoup): The BeautifulSoup object 13 | base_url (str): The base URL 14 | 15 | Returns: 16 | List[Tuple[str, str]]: The extracted hyperlinks 17 | """ 18 | return [ 19 | (link.text, urljoin(base_url, link["href"])) 20 | for link in soup.find_all("a", href=True) 21 | ] 22 | 23 | 24 | def format_hyperlinks(hyperlinks: list[tuple[str, str]]) -> list[str]: 25 | """Format hyperlinks to be displayed to the user 26 | 27 | Args: 28 | hyperlinks (List[Tuple[str, str]]): The hyperlinks to format 29 | 30 | Returns: 31 | List[str]: The formatted hyperlinks 32 | """ 33 | return [f"{link_text} ({link_url})" for link_text, link_url in hyperlinks] 34 | -------------------------------------------------------------------------------- /autogpt/processing/text.py: -------------------------------------------------------------------------------- 1 | """Text processing functions""" 2 | from typing import Generator, Optional, Dict 3 | from selenium.webdriver.remote.webdriver import WebDriver 4 | from autogpt.memory import get_memory 5 | from autogpt.config import Config 6 | from autogpt.llm_utils import create_chat_completion 7 | 8 | CFG = Config() 9 | MEMORY = get_memory(CFG) 10 | 11 | 12 | def split_text(text: str, max_length: int = 8192) -> Generator[str, None, None]: 13 | """Split text into chunks of a maximum length 14 | 15 | Args: 16 | text (str): The text to split 17 | max_length (int, optional): The maximum length of each chunk. Defaults to 8192. 18 | 19 | Yields: 20 | str: The next chunk of text 21 | 22 | Raises: 23 | ValueError: If the text is longer than the maximum length 24 | """ 25 | paragraphs = text.split("\n") 26 | current_length = 0 27 | current_chunk = [] 28 | 29 | for paragraph in paragraphs: 30 | if current_length + len(paragraph) + 1 <= max_length: 31 | current_chunk.append(paragraph) 32 | current_length += len(paragraph) + 1 33 | else: 34 | yield "\n".join(current_chunk) 35 | current_chunk = [paragraph] 36 | current_length = len(paragraph) + 1 37 | 38 | if current_chunk: 39 | yield "\n".join(current_chunk) 40 | 41 | 42 | def summarize_text( 43 | url: str, text: str, question: str, driver: Optional[WebDriver] = None 44 | ) -> str: 45 | """Summarize text using the OpenAI API 46 | 47 | Args: 48 | url (str): The url of the text 49 | text (str): The text to summarize 50 | question (str): The question to ask the model 51 | driver (WebDriver): The webdriver to use to scroll the page 52 | 53 | Returns: 54 | str: The summary of the text 55 | """ 56 | if not text: 57 | return "Error: No text to summarize" 58 | 59 | text_length = len(text) 60 | print(f"Text length: {text_length} characters") 61 | 62 | summaries = [] 63 | chunks = list(split_text(text)) 64 | scroll_ratio = 1 / len(chunks) 65 | 66 | for i, chunk in enumerate(chunks): 67 | if driver: 68 | scroll_to_percentage(driver, scroll_ratio * i) 69 | print(f"Adding chunk {i + 1} / {len(chunks)} to memory") 70 | 71 | memory_to_add = f"Source: {url}\n" f"Raw content part#{i + 1}: {chunk}" 72 | 73 | MEMORY.add(memory_to_add) 74 | 75 | print(f"Summarizing chunk {i + 1} / {len(chunks)}") 76 | messages = [create_message(chunk, question)] 77 | 78 | summary = create_chat_completion( 79 | model=CFG.fast_llm_model, 80 | messages=messages, 81 | max_tokens=CFG.browse_summary_max_token, 82 | ) 83 | summaries.append(summary) 84 | print(f"Added chunk {i + 1} summary to memory") 85 | 86 | memory_to_add = f"Source: {url}\n" f"Content summary part#{i + 1}: {summary}" 87 | 88 | MEMORY.add(memory_to_add) 89 | 90 | print(f"Summarized {len(chunks)} chunks.") 91 | 92 | combined_summary = "\n".join(summaries) 93 | messages = [create_message(combined_summary, question)] 94 | 95 | return create_chat_completion( 96 | model=CFG.fast_llm_model, 97 | messages=messages, 98 | max_tokens=CFG.browse_summary_max_token, 99 | ) 100 | 101 | 102 | def scroll_to_percentage(driver: WebDriver, ratio: float) -> None: 103 | """Scroll to a percentage of the page 104 | 105 | Args: 106 | driver (WebDriver): The webdriver to use 107 | ratio (float): The percentage to scroll to 108 | 109 | Raises: 110 | ValueError: If the ratio is not between 0 and 1 111 | """ 112 | if ratio < 0 or ratio > 1: 113 | raise ValueError("Percentage should be between 0 and 1") 114 | driver.execute_script(f"window.scrollTo(0, document.body.scrollHeight * {ratio});") 115 | 116 | 117 | def create_message(chunk: str, question: str) -> Dict[str, str]: 118 | """Create a message for the chat completion 119 | 120 | Args: 121 | chunk (str): The chunk of text to summarize 122 | question (str): The question to answer 123 | 124 | Returns: 125 | Dict[str, str]: The message to send to the chat completion 126 | """ 127 | return { 128 | "role": "user", 129 | "content": f'"""{chunk}""" Using the above text, answer the following' 130 | f' question: "{question}" -- if the question cannot be answered using the text,' 131 | " summarize the text.", 132 | } 133 | -------------------------------------------------------------------------------- /autogpt/setup.py: -------------------------------------------------------------------------------- 1 | """Setup the AI and its goals""" 2 | from colorama import Fore, Style 3 | from autogpt import utils 4 | from autogpt.config.ai_config import AIConfig 5 | from autogpt.logs import logger 6 | 7 | 8 | def prompt_user() -> AIConfig: 9 | """Prompt the user for input 10 | 11 | Returns: 12 | AIConfig: The AIConfig object containing the user's input 13 | """ 14 | ai_name = "" 15 | # Construct the prompt 16 | logger.typewriter_log( 17 | "欢迎来到 Auto-GPT-ZH! 中文版由AJ提供. ", 18 | Fore.GREEN, 19 | "", 20 | speak_text=True, 21 | ) 22 | logger.typewriter_log( 23 | "公众号《阿杰的人生路》回复Auto-GPT,加入社区共同探讨使用方式.", 24 | Fore.YELLOW, 25 | "", 26 | speak_text=True, 27 | ) 28 | 29 | print("在下面输入您的 AI 的名称及其角色。不输入将使用默认名称") 30 | # Get AI Name from User 31 | logger.typewriter_log( 32 | "为您的 AI 命名:",Fore.GREEN,"例如,'AJ-1号-GPT'" 33 | ) 34 | ai_name = utils.clean_input("AI 机器人名称: ") 35 | if ai_name == "": 36 | ai_name = "AJ-1号-GPT" 37 | 38 | logger.typewriter_log( 39 | f"{ai_name} 在这里!", Fore.LIGHTBLUE_EX, "我随时为您服务。", speak_text=True 40 | ) 41 | 42 | # Get AI Role from User 43 | logger.typewriter_log( 44 | "描述您的 AI 的职责:", 45 | Fore.GREEN, 46 | "例如,'一种旨在自主开发和经营业务的人工智能,其唯一目标是增加你的净资产。" 47 | ) 48 | ai_role = utils.clean_input(f"{ai_name} 的职责: ") 49 | if ai_role == "": 50 | ai_role = "一个旨在自主开发和经营企业以唯一目标增加你净值的人工智能" 51 | 52 | # Enter up to 5 goals for the AI 53 | logger.typewriter_log( 54 | "提示:输入最多5个要帮你实现的功能/目标 ", 55 | Fore.GREEN, 56 | "例如:\n增加公众号关注者、市场调研、自主开发网站等等") 57 | print("输入空白以加载默认值,完成时不要输入任何内容。", flush=True) 58 | ai_goals = [] 59 | for i in range(5): 60 | ai_goal = utils.clean_input(f"{Fore.LIGHTBLUE_EX}Goal{Style.RESET_ALL} {i+1}: ") 61 | if ai_goal == "": 62 | break 63 | ai_goals.append(ai_goal) 64 | if len(ai_goals) == 0: 65 | ai_goals = [ 66 | "Increase net worth", 67 | "Grow Twitter Account", 68 | "Develop and manage multiple businesses autonomously", 69 | ] 70 | 71 | return AIConfig(ai_name, ai_role, ai_goals) 72 | -------------------------------------------------------------------------------- /autogpt/speak.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import requests 4 | from playsound import playsound 5 | 6 | from autogpt.config import Config 7 | 8 | import threading 9 | from threading import Lock, Semaphore 10 | 11 | import gtts 12 | 13 | cfg = Config() 14 | 15 | # Default voice IDs 16 | default_voices = ["ErXwobaYiN019PkySvjV", "EXAVITQu4vr4xnSDxMaL"] 17 | 18 | # Retrieve custom voice IDs from the Config class 19 | custom_voice_1 = cfg.elevenlabs_voice_1_id 20 | custom_voice_2 = cfg.elevenlabs_voice_2_id 21 | 22 | # Placeholder values that should be treated as empty 23 | placeholders = {"your-voice-id"} 24 | 25 | # Use custom voice IDs if provided and not placeholders, otherwise use default voice IDs 26 | voices = [ 27 | custom_voice_1 28 | if custom_voice_1 and custom_voice_1 not in placeholders 29 | else default_voices[0], 30 | custom_voice_2 31 | if custom_voice_2 and custom_voice_2 not in placeholders 32 | else default_voices[1], 33 | ] 34 | 35 | tts_headers = {"Content-Type": "application/json", "xi-api-key": cfg.elevenlabs_api_key} 36 | 37 | mutex_lock = Lock() # Ensure only one sound is played at a time 38 | queue_semaphore = Semaphore( 39 | 1 40 | ) # The amount of sounds to queue before blocking the main thread 41 | 42 | 43 | def eleven_labs_speech(text, voice_index=0): 44 | """使用elevenlabs.io的API朗读文本""" 45 | tts_url = "https://api.elevenlabs.io/v1/text-to-speech/{voice_id}".format( 46 | voice_id=voices[voice_index] 47 | ) 48 | formatted_message = {"text": text} 49 | response = requests.post(tts_url, headers=tts_headers, json=formatted_message) 50 | 51 | if response.status_code == 200: 52 | with mutex_lock: 53 | with open("speech.mpeg", "wb") as f: 54 | f.write(response.content) 55 | playsound("speech.mpeg", True) 56 | os.remove("speech.mpeg") 57 | return True 58 | else: 59 | print("请求失败,状态码为:", response.status_code) 60 | print("响应内容:", response.content) 61 | return False 62 | 63 | 64 | def brian_speech(text): 65 | """Speak text using Brian with the streamelements API""" 66 | tts_url = f"https://api.streamelements.com/kappa/v2/speech?voice=Brian&text={text}" 67 | response = requests.get(tts_url) 68 | 69 | if response.status_code == 200: 70 | with mutex_lock: 71 | with open("speech.mp3", "wb") as f: 72 | f.write(response.content) 73 | playsound("speech.mp3") 74 | os.remove("speech.mp3") 75 | return True 76 | else: 77 | print("Request failed with status code:", response.status_code) 78 | print("Response content:", response.content) 79 | return False 80 | 81 | 82 | def gtts_speech(text): 83 | tts = gtts.gTTS(text) 84 | with mutex_lock: 85 | tts.save("speech.mp3") 86 | playsound("speech.mp3", True) 87 | os.remove("speech.mp3") 88 | 89 | 90 | def macos_tts_speech(text, voice_index=0): 91 | if voice_index == 0: 92 | os.system(f'say "{text}"') 93 | else: 94 | if voice_index == 1: 95 | os.system(f'say -v "Ava (Premium)" "{text}"') 96 | else: 97 | os.system(f'say -v Samantha "{text}"') 98 | 99 | 100 | def say_text(text, voice_index=0): 101 | def speak(): 102 | if not cfg.elevenlabs_api_key: 103 | if cfg.use_mac_os_tts == "True": 104 | macos_tts_speech(text) 105 | elif cfg.use_brian_tts == "True": 106 | success = brian_speech(text) 107 | if not success: 108 | gtts_speech(text) 109 | else: 110 | gtts_speech(text) 111 | else: 112 | success = eleven_labs_speech(text, voice_index) 113 | if not success: 114 | gtts_speech(text) 115 | 116 | queue_semaphore.release() 117 | 118 | queue_semaphore.acquire(True) 119 | thread = threading.Thread(target=speak) 120 | thread.start() 121 | -------------------------------------------------------------------------------- /autogpt/speech/__init__.py: -------------------------------------------------------------------------------- 1 | """This module contains the speech recognition and speech synthesis functions.""" 2 | from autogpt.speech.say import say_text 3 | 4 | __all__ = ["say_text"] 5 | -------------------------------------------------------------------------------- /autogpt/speech/base.py: -------------------------------------------------------------------------------- 1 | """Base class for all voice classes.""" 2 | import abc 3 | from threading import Lock 4 | 5 | from autogpt.config import AbstractSingleton 6 | 7 | 8 | class VoiceBase(AbstractSingleton): 9 | """ 10 | Base class for all voice classes. 11 | """ 12 | 13 | def __init__(self): 14 | """ 15 | Initialize the voice class. 16 | """ 17 | self._url = None 18 | self._headers = None 19 | self._api_key = None 20 | self._voices = [] 21 | self._mutex = Lock() 22 | self._setup() 23 | 24 | def say(self, text: str, voice_index: int = 0) -> bool: 25 | """ 26 | Say the given text. 27 | 28 | Args: 29 | text (str): The text to say. 30 | voice_index (int): The index of the voice to use. 31 | """ 32 | with self._mutex: 33 | return self._speech(text, voice_index) 34 | 35 | @abc.abstractmethod 36 | def _setup(self) -> None: 37 | """ 38 | Setup the voices, API key, etc. 39 | """ 40 | pass 41 | 42 | @abc.abstractmethod 43 | def _speech(self, text: str, voice_index: int = 0) -> bool: 44 | """ 45 | Play the given text. 46 | 47 | Args: 48 | text (str): The text to play. 49 | """ 50 | pass 51 | -------------------------------------------------------------------------------- /autogpt/speech/brian.py: -------------------------------------------------------------------------------- 1 | """ Brian speech module for autogpt """ 2 | import os 3 | import requests 4 | from playsound import playsound 5 | 6 | from autogpt.speech.base import VoiceBase 7 | 8 | 9 | class BrianSpeech(VoiceBase): 10 | """Brian speech module for autogpt""" 11 | 12 | def _setup(self) -> None: 13 | """Setup the voices, API key, etc.""" 14 | pass 15 | 16 | def _speech(self, text: str) -> bool: 17 | """Speak text using Brian with the streamelements API 18 | 19 | Args: 20 | text (str): The text to speak 21 | 22 | Returns: 23 | bool: True if the request was successful, False otherwise 24 | """ 25 | tts_url = ( 26 | f"https://api.streamelements.com/kappa/v2/speech?voice=Brian&text={text}" 27 | ) 28 | response = requests.get(tts_url) 29 | 30 | if response.status_code == 200: 31 | with open("speech.mp3", "wb") as f: 32 | f.write(response.content) 33 | playsound("speech.mp3") 34 | os.remove("speech.mp3") 35 | return True 36 | else: 37 | print("Request failed with status code:", response.status_code) 38 | print("Response content:", response.content) 39 | return False 40 | -------------------------------------------------------------------------------- /autogpt/speech/eleven_labs.py: -------------------------------------------------------------------------------- 1 | """ElevenLabs speech module""" 2 | import os 3 | from playsound import playsound 4 | 5 | import requests 6 | 7 | from autogpt.config import Config 8 | from autogpt.speech.base import VoiceBase 9 | 10 | PLACEHOLDERS = {"your-voice-id"} 11 | 12 | 13 | class ElevenLabsSpeech(VoiceBase): 14 | """ElevenLabs speech class""" 15 | 16 | def _setup(self) -> None: 17 | """Setup the voices, API key, etc. 18 | 19 | Returns: 20 | None: None 21 | """ 22 | 23 | cfg = Config() 24 | default_voices = ["ErXwobaYiN019PkySvjV", "EXAVITQu4vr4xnSDxMaL"] 25 | voice_options = { 26 | "Rachel": "21m00Tcm4TlvDq8ikWAM", 27 | "Domi": "AZnzlk1XvdvUeBnXmlld", 28 | "Bella": "EXAVITQu4vr4xnSDxMaL", 29 | "Antoni": "ErXwobaYiN019PkySvjV", 30 | "Elli": "MF3mGyEYCl7XYWbV9V6O", 31 | "Josh": "TxGEqnHWrfWFTfGW9XjX", 32 | "Arnold": "VR6AewLTigWG4xSOukaG", 33 | "Adam": "pNInz6obpgDQGcFmaJgB", 34 | "Sam": "yoZ06aMxZJJ28mfd3POQ", 35 | } 36 | self._headers = { 37 | "Content-Type": "application/json", 38 | "xi-api-key": cfg.elevenlabs_api_key, 39 | } 40 | self._voices = default_voices.copy() 41 | if cfg.elevenlabs_voice_1_id in voice_options: 42 | cfg.elevenlabs_voice_1_id = voice_options[cfg.elevenlabs_voice_1_id] 43 | if cfg.elevenlabs_voice_2_id in voice_options: 44 | cfg.elevenlabs_voice_2_id = voice_options[cfg.elevenlabs_voice_2_id] 45 | self._use_custom_voice(cfg.elevenlabs_voice_1_id, 0) 46 | self._use_custom_voice(cfg.elevenlabs_voice_2_id, 1) 47 | 48 | def _use_custom_voice(self, voice, voice_index) -> None: 49 | """Use a custom voice if provided and not a placeholder 50 | 51 | Args: 52 | voice (str): The voice ID 53 | voice_index (int): The voice index 54 | 55 | Returns: 56 | None: None 57 | """ 58 | # Placeholder values that should be treated as empty 59 | if voice and voice not in PLACEHOLDERS: 60 | self._voices[voice_index] = voice 61 | 62 | def _speech(self, text: str, voice_index: int = 0) -> bool: 63 | """Speak text using elevenlabs.io's API 64 | 65 | Args: 66 | text (str): The text to speak 67 | voice_index (int, optional): The voice to use. Defaults to 0. 68 | 69 | Returns: 70 | bool: True if the request was successful, False otherwise 71 | """ 72 | tts_url = ( 73 | f"https://api.elevenlabs.io/v1/text-to-speech/{self._voices[voice_index]}" 74 | ) 75 | response = requests.post(tts_url, headers=self._headers, json={"text": text}) 76 | 77 | if response.status_code == 200: 78 | with open("speech.mpeg", "wb") as f: 79 | f.write(response.content) 80 | playsound("speech.mpeg", True) 81 | os.remove("speech.mpeg") 82 | return True 83 | else: 84 | print("Request failed with status code:", response.status_code) 85 | print("Response content:", response.content) 86 | return False 87 | -------------------------------------------------------------------------------- /autogpt/speech/gtts.py: -------------------------------------------------------------------------------- 1 | """ GTTS Voice. """ 2 | import os 3 | from playsound import playsound 4 | import gtts 5 | 6 | from autogpt.speech.base import VoiceBase 7 | 8 | 9 | class GTTSVoice(VoiceBase): 10 | """GTTS Voice.""" 11 | 12 | def _setup(self) -> None: 13 | pass 14 | 15 | def _speech(self, text: str, _: int = 0) -> bool: 16 | """Play the given text.""" 17 | tts = gtts.gTTS(text) 18 | tts.save("speech.mp3") 19 | playsound("speech.mp3", True) 20 | os.remove("speech.mp3") 21 | return True 22 | -------------------------------------------------------------------------------- /autogpt/speech/macos_tts.py: -------------------------------------------------------------------------------- 1 | """ MacOS TTS Voice. """ 2 | import os 3 | 4 | from autogpt.speech.base import VoiceBase 5 | 6 | 7 | class MacOSTTS(VoiceBase): 8 | """MacOS TTS Voice.""" 9 | 10 | def _setup(self) -> None: 11 | pass 12 | 13 | def _speech(self, text: str, voice_index: int = 0) -> bool: 14 | """Play the given text.""" 15 | if voice_index == 0: 16 | os.system(f'say "{text}"') 17 | elif voice_index == 1: 18 | os.system(f'say -v "Ava (Premium)" "{text}"') 19 | else: 20 | os.system(f'say -v Samantha "{text}"') 21 | return True 22 | -------------------------------------------------------------------------------- /autogpt/speech/say.py: -------------------------------------------------------------------------------- 1 | """ Text to speech module """ 2 | from autogpt.config import Config 3 | 4 | import threading 5 | from threading import Semaphore 6 | from autogpt.speech.brian import BrianSpeech 7 | from autogpt.speech.macos_tts import MacOSTTS 8 | from autogpt.speech.gtts import GTTSVoice 9 | from autogpt.speech.eleven_labs import ElevenLabsSpeech 10 | 11 | 12 | CFG = Config() 13 | DEFAULT_VOICE_ENGINE = GTTSVoice() 14 | VOICE_ENGINE = None 15 | if CFG.elevenlabs_api_key: 16 | VOICE_ENGINE = ElevenLabsSpeech() 17 | elif CFG.use_mac_os_tts == "True": 18 | VOICE_ENGINE = MacOSTTS() 19 | elif CFG.use_brian_tts == "True": 20 | VOICE_ENGINE = BrianSpeech() 21 | else: 22 | VOICE_ENGINE = GTTSVoice() 23 | 24 | 25 | QUEUE_SEMAPHORE = Semaphore( 26 | 1 27 | ) # The amount of sounds to queue before blocking the main thread 28 | 29 | 30 | def say_text(text: str, voice_index: int = 0) -> None: 31 | """Speak the given text using the given voice index""" 32 | 33 | def speak() -> None: 34 | success = VOICE_ENGINE.say(text, voice_index) 35 | if not success: 36 | DEFAULT_VOICE_ENGINE.say(text) 37 | 38 | QUEUE_SEMAPHORE.release() 39 | 40 | QUEUE_SEMAPHORE.acquire(True) 41 | thread = threading.Thread(target=speak) 42 | thread.start() 43 | -------------------------------------------------------------------------------- /autogpt/spinner.py: -------------------------------------------------------------------------------- 1 | """A simple spinner module""" 2 | import itertools 3 | import sys 4 | import threading 5 | import time 6 | 7 | 8 | class Spinner: 9 | """A simple spinner class""" 10 | 11 | def __init__(self, message: str = "Loading...", delay: float = 0.1) -> None: 12 | """Initialize the spinner class 13 | 14 | Args: 15 | message (str): The message to display. 16 | delay (float): The delay between each spinner update. 17 | """ 18 | self.spinner = itertools.cycle(["-", "/", "|", "\\"]) 19 | self.delay = delay 20 | self.message = message 21 | self.running = False 22 | self.spinner_thread = None 23 | 24 | def spin(self) -> None: 25 | """Spin the spinner""" 26 | while self.running: 27 | sys.stdout.write(f"{next(self.spinner)} {self.message}\r") 28 | sys.stdout.flush() 29 | time.sleep(self.delay) 30 | sys.stdout.write(f"\r{' ' * (len(self.message) + 2)}\r") 31 | 32 | def __enter__(self) -> None: 33 | """Start the spinner""" 34 | self.running = True 35 | self.spinner_thread = threading.Thread(target=self.spin) 36 | self.spinner_thread.start() 37 | 38 | def __exit__(self, exc_type, exc_value, exc_traceback) -> None: 39 | """Stop the spinner 40 | 41 | Args: 42 | exc_type (Exception): The exception type. 43 | exc_value (Exception): The exception value. 44 | exc_traceback (Exception): The exception traceback. 45 | """ 46 | self.running = False 47 | if self.spinner_thread is not None: 48 | self.spinner_thread.join() 49 | sys.stdout.write(f"\r{' ' * (len(self.message) + 2)}\r") 50 | sys.stdout.flush() 51 | -------------------------------------------------------------------------------- /autogpt/summary.py: -------------------------------------------------------------------------------- 1 | from autogpt.llm_utils import create_chat_completion 2 | 3 | 4 | def summarize_text(driver, text, question): 5 | if not text: 6 | return "Error: 没有可总结的文本" 7 | 8 | text_length = len(text) 9 | print(f"文字长度: {text_length} 字符") 10 | 11 | summaries = [] 12 | chunks = list(split_text(text)) 13 | 14 | scroll_ratio = 1 / len(chunks) 15 | for i, chunk in enumerate(chunks): 16 | scroll_to_percentage(driver, scroll_ratio * i) 17 | print(f"总结中 {i + 1} / {len(chunks)}") 18 | messages = [create_message(chunk, question)] 19 | 20 | summary = create_chat_completion( 21 | model="gpt-3.5-turbo", 22 | messages=messages, 23 | max_tokens=300, 24 | ) 25 | summaries.append(summary) 26 | 27 | print(f"已总结 {len(chunks)}.") 28 | 29 | combined_summary = "\n".join(summaries) 30 | messages = [create_message(combined_summary, question)] 31 | 32 | return create_chat_completion( 33 | model="gpt-3.5-turbo", 34 | messages=messages, 35 | max_tokens=300, 36 | ) 37 | 38 | 39 | def split_text(text, max_length=8192): 40 | paragraphs = text.split("\n") 41 | current_length = 0 42 | current_chunk = [] 43 | 44 | for paragraph in paragraphs: 45 | if current_length + len(paragraph) + 1 <= max_length: 46 | current_chunk.append(paragraph) 47 | current_length += len(paragraph) + 1 48 | else: 49 | yield "\n".join(current_chunk) 50 | current_chunk = [paragraph] 51 | current_length = len(paragraph) + 1 52 | 53 | if current_chunk: 54 | yield "\n".join(current_chunk) 55 | 56 | 57 | def create_message(chunk, question): 58 | return { 59 | "role": "user", 60 | "content": f'"""{chunk}""" 使用以上文本,请以中文回答以下问题:' 61 | f' question: "{question}" -- if the question cannot be answered using the text,' 62 | " please summarize the text.", 63 | } 64 | 65 | 66 | def scroll_to_percentage(driver, ratio): 67 | if ratio < 0 or ratio > 1: 68 | raise ValueError("百分比应该在 0 和 1 之间") 69 | driver.execute_script(f"window.scrollTo(0, document.body.scrollHeight * {ratio});") 70 | -------------------------------------------------------------------------------- /autogpt/token_counter.py: -------------------------------------------------------------------------------- 1 | """Functions for counting the number of tokens in a message or string.""" 2 | from __future__ import annotations 3 | 4 | import tiktoken 5 | 6 | from autogpt.logs import logger 7 | 8 | 9 | def count_message_tokens( 10 | messages: list[dict[str, str]], model: str = "gpt-3.5-turbo-0301" 11 | ) -> int: 12 | """ 13 | Returns the number of tokens used by a list of messages. 14 | 15 | Args: 16 | messages (list): A list of messages, each of which is a dictionary 17 | containing the role and content of the message. 18 | model (str): The name of the model to use for tokenization. 19 | Defaults to "gpt-3.5-turbo-0301". 20 | 21 | Returns: 22 | int: The number of tokens used by the list of messages. 23 | """ 24 | try: 25 | encoding = tiktoken.encoding_for_model(model) 26 | except KeyError: 27 | logger.warn("Warning:未找到模型。使用 cl100k_base 编码。") 28 | encoding = tiktoken.get_encoding("cl100k_base") 29 | if model == "gpt-3.5-turbo": 30 | # !Note: gpt-3.5-turbo may change over time. 31 | # Returning num tokens assuming gpt-3.5-turbo-0301.") 32 | return count_message_tokens(messages, model="gpt-3.5-turbo-0301") 33 | elif model == "gpt-4": 34 | # !Note: gpt-4 may change over time. Returning num tokens assuming gpt-4-0314.") 35 | return count_message_tokens(messages, model="gpt-4-0314") 36 | elif model == "gpt-3.5-turbo-0301": 37 | tokens_per_message = ( 38 | 4 # every message follows <|start|>{role/name}\n{content}<|end|>\n 39 | ) 40 | tokens_per_name = -1 # if there's a name, the role is omitted 41 | elif model == "gpt-4-0314": 42 | tokens_per_message = 3 43 | tokens_per_name = 1 44 | else: 45 | raise NotImplementedError( 46 | f"num_tokens_from_messages() is not implemented for model {model}.\n" 47 | " See https://github.com/openai/openai-python/blob/main/chatml.md for" 48 | " information on how messages are converted to tokens." 49 | ) 50 | num_tokens = 0 51 | for message in messages: 52 | num_tokens += tokens_per_message 53 | for key, value in message.items(): 54 | num_tokens += len(encoding.encode(value)) 55 | if key == "name": 56 | num_tokens += tokens_per_name 57 | num_tokens += 3 # every reply is primed with <|start|>assistant<|message|> 58 | return num_tokens 59 | 60 | 61 | def count_string_tokens(string: str, model_name: str) -> int: 62 | """ 63 | Returns the number of tokens in a text string. 64 | 65 | Args: 66 | string (str): The text string. 67 | model_name (str): The name of the encoding to use. (e.g., "gpt-3.5-turbo") 68 | 69 | Returns: 70 | int: The number of tokens in the text string. 71 | """ 72 | encoding = tiktoken.encoding_for_model(model_name) 73 | return len(encoding.encode(string)) 74 | -------------------------------------------------------------------------------- /autogpt/utils.py: -------------------------------------------------------------------------------- 1 | import yaml 2 | from colorama import Fore 3 | 4 | 5 | def clean_input(prompt: str = ""): 6 | try: 7 | return input(prompt) 8 | except KeyboardInterrupt: 9 | print("您中断了 Auto-GPT") 10 | print("退出...") 11 | exit(0) 12 | 13 | 14 | def validate_yaml_file(file: str): 15 | try: 16 | with open(file, encoding="utf-8") as fp: 17 | yaml.load(fp.read(), Loader=yaml.FullLoader) 18 | except FileNotFoundError: 19 | return (False, f"文件 {Fore.CYAN}`{file}`{Fore.RESET} 没有找到") 20 | except yaml.YAMLError as e: 21 | return ( 22 | False, 23 | f"尝试读取 AI 设置文件时出现问题: {e}", 24 | ) 25 | 26 | return (True, f"Successfully validated {Fore.CYAN}`{file}`{Fore.RESET}!") 27 | -------------------------------------------------------------------------------- /autogpt/web.py: -------------------------------------------------------------------------------- 1 | from selenium import webdriver 2 | import autogpt.summary as summary 3 | from bs4 import BeautifulSoup 4 | from selenium.webdriver.common.by import By 5 | from selenium.webdriver.support.wait import WebDriverWait 6 | from selenium.webdriver.support import expected_conditions as EC 7 | from webdriver_manager.chrome import ChromeDriverManager 8 | from selenium.webdriver.chrome.options import Options 9 | import logging 10 | from pathlib import Path 11 | from autogpt.config import Config 12 | 13 | file_dir = Path(__file__).parent 14 | cfg = Config() 15 | 16 | 17 | def browse_website(url, question): 18 | driver, text = scrape_text_with_selenium(url) 19 | add_header(driver) 20 | summary_text = summary.summarize_text(driver, text, question) 21 | links = scrape_links_with_selenium(driver) 22 | 23 | # Limit links to 5 24 | if len(links) > 5: 25 | links = links[:5] 26 | close_browser(driver) 27 | return f"从网站收集的答案: {summary_text} \n \n 链接: {links}", driver 28 | 29 | 30 | def scrape_text_with_selenium(url): 31 | logging.getLogger("selenium").setLevel(logging.CRITICAL) 32 | 33 | options = Options() 34 | options.add_argument( 35 | "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" 36 | ) 37 | driver = webdriver.Chrome( 38 | executable_path=ChromeDriverManager().install(), options=options 39 | ) 40 | driver.get(url) 41 | 42 | WebDriverWait(driver, 10).until( 43 | EC.presence_of_element_located((By.TAG_NAME, "body")) 44 | ) 45 | 46 | # Get the HTML content directly from the browser's DOM 47 | page_source = driver.execute_script("return document.body.outerHTML;") 48 | soup = BeautifulSoup(page_source, "html.parser") 49 | 50 | for script in soup(["script", "style"]): 51 | script.extract() 52 | 53 | text = soup.get_text() 54 | lines = (line.strip() for line in text.splitlines()) 55 | chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) 56 | text = "\n".join(chunk for chunk in chunks if chunk) 57 | return driver, text 58 | 59 | 60 | def scrape_links_with_selenium(driver): 61 | page_source = driver.page_source 62 | soup = BeautifulSoup(page_source, "html.parser") 63 | 64 | for script in soup(["script", "style"]): 65 | script.extract() 66 | 67 | hyperlinks = extract_hyperlinks(soup) 68 | 69 | return format_hyperlinks(hyperlinks) 70 | 71 | 72 | def close_browser(driver): 73 | driver.quit() 74 | 75 | 76 | def extract_hyperlinks(soup): 77 | return [(link.text, link["href"]) for link in soup.find_all("a", href=True)] 78 | 79 | 80 | def format_hyperlinks(hyperlinks): 81 | return [f"{link_text} ({link_url})" for link_text, link_url in hyperlinks] 82 | 83 | 84 | def add_header(driver): 85 | driver.execute_script(open(f"{file_dir}/js/overlay.js", "r").read()) 86 | -------------------------------------------------------------------------------- /autogpt/workspace.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | from pathlib import Path 5 | 6 | # Set a dedicated folder for file I/O 7 | WORKSPACE_PATH = Path(os.getcwd()) / "auto_gpt_workspace" 8 | 9 | # Create the directory if it doesn't exist 10 | if not os.path.exists(WORKSPACE_PATH): 11 | os.makedirs(WORKSPACE_PATH) 12 | 13 | 14 | def path_in_workspace(relative_path: str | Path) -> Path: 15 | """Get full path for item in workspace 16 | 17 | Parameters: 18 | relative_path (str | Path): Path to translate into the workspace 19 | 20 | Returns: 21 | Path: Absolute path for the given path in the workspace 22 | """ 23 | return safe_path_join(WORKSPACE_PATH, relative_path) 24 | 25 | 26 | def safe_path_join(base: Path, *paths: str | Path) -> Path: 27 | """Join one or more path components, asserting the resulting path is within the workspace. 28 | 29 | Args: 30 | base (Path): The base path 31 | *paths (str): The paths to join to the base path 32 | 33 | Returns: 34 | Path: The joined path 35 | """ 36 | joined_path = base.joinpath(*paths).resolve() 37 | 38 | if not joined_path.is_relative_to(base): 39 | raise ValueError(f"Attempted to access path '{joined_path}' outside of working directory '{base}'.") 40 | 41 | return joined_path 42 | -------------------------------------------------------------------------------- /azure.yaml.template: -------------------------------------------------------------------------------- 1 | azure_api_type: azure_ad 2 | azure_api_base: your-base-url-for-azure 3 | azure_api_version: api-version-for-azure 4 | azure_model_map: 5 | fast_llm_model_deployment_id: gpt35-deployment-id-for-azure 6 | smart_llm_model_deployment_id: gpt4-deployment-id-for-azure 7 | embedding_model_deployment_id: embedding-deployment-id-for-azure 8 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | # To boot the app run the following: 2 | # docker-compose run auto-gpt 3 | version: "3.9" 4 | 5 | services: 6 | auto-gpt: 7 | depends_on: 8 | - redis 9 | build: ./ 10 | env_file: 11 | - .env 12 | volumes: 13 | - "./autogpt:/app" 14 | - ".env:/app/.env" 15 | profiles: ["exclude-from-up"] 16 | 17 | redis: 18 | image: "redis/redis-stack-server:latest" 19 | -------------------------------------------------------------------------------- /docs/imgs/demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaqijiang/Auto-GPT-aj/310a84c8ca0173c7db43f637866cf5677bd7ef50/docs/imgs/demo.gif -------------------------------------------------------------------------------- /docs/imgs/gzh.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaqijiang/Auto-GPT-aj/310a84c8ca0173c7db43f637866cf5677bd7ef50/docs/imgs/gzh.png -------------------------------------------------------------------------------- /docs/imgs/openai-api-key-billing-paid-account.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaqijiang/Auto-GPT-aj/310a84c8ca0173c7db43f637866cf5677bd7ef50/docs/imgs/openai-api-key-billing-paid-account.png -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | from autogpt import main 2 | -------------------------------------------------------------------------------- /openai-api-key.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaqijiang/Auto-GPT-aj/310a84c8ca0173c7db43f637866cf5677bd7ef50/openai-api-key.png -------------------------------------------------------------------------------- /outputs/guest_post_email.txt: -------------------------------------------------------------------------------- 1 | Subject: Exciting Collaboration Opportunity: FinanceGPT.substack.com Guest Post 2 | 3 | Dear [Popular Blog Owner], 4 | 5 | I hope this email finds you well. My name is [Your Name] and I'm the founder and writer of FinanceGPT.substack.com, a new personal finance and investing blog that focuses on leveraging AI technology to provide in-depth analysis, actionable tips, and innovative perspectives on personal finance management. 6 | 7 | First and foremost, I want to say that I'm a huge admirer of your blog, [Popular Blog Name]. Your insightful content and dedication to helping people achieve financial success have inspired me to create my own platform. As a fellow personal finance enthusiast, I would like to propose a collaboration in the form of a guest post on your blog. I believe that my fresh take on personal finance, combined with the innovative use of AI, would make a valuable addition to your already impressive content lineup. 8 | 9 | Here are some potential guest post topics that I think your audience would enjoy: 10 | 11 | Harnessing AI to Streamline Personal Finance: How to maximize efficiency and optimize your financial management using cutting-edge AI tools. 12 | Unraveling the Secrets of the Stock Market with AI: Insights into stock analysis and investment strategies, backed by machine learning algorithms. 13 | The Future of Financial Independence: Exploring the impact of AI on the FIRE (Financial Independence, Retire Early) movement. 14 | Sustainable Investing in the Age of AI: Identifying eco-friendly investment opportunities with the help of machine learning. 15 | By collaborating on a guest post, we both stand to benefit in several ways: 16 | 17 | Audience Growth: By sharing our expertise with each other's audiences, we can broaden our reach and help even more people achieve their financial goals. 18 | Cross-Promotion: We can promote each other's content, thus increasing brand exposure and attracting new subscribers to our respective platforms. 19 | Knowledge Sharing: Combining our unique perspectives and experiences will enrich the quality of our content, providing readers with comprehensive and diverse information. 20 | If you are interested in this collaboration, I would be more than happy to provide you with a detailed outline for any of the proposed topics or discuss any other ideas you may have. Please let me know your thoughts, and I look forward to the possibility of working together. 21 | 22 | Thank you for your time and consideration. 23 | 24 | Best regards, 25 | 26 | [Your Name] 27 | Founder and Writer, FinanceGPT.substack.com 28 | Email: [Your Email Address] 29 | Phone: [Your Phone Number] -------------------------------------------------------------------------------- /outputs/how_to_save_money_on_energy_bills.txt: -------------------------------------------------------------------------------- 1 | How to Save Money on Energy Bills: Easy and Affordable Solutions 2 | 3 | Electricity bills can skyrocket during harsh weather conditions, or when we use a lot of electronic devices. When energy bills go up, it's hard to tighten up our budget without sacrificing our home comforts. However, there are affordable ways to save money on energy bills, without turning off the electricity altogether. Here are some simple solutions that can help you lower your energy expenses. 4 | 5 | 1. Install a Programmable Thermostat 6 | 7 | Maintaining an optimal temperature in your home during summer or winter can be hard; you may either overheat your home or use heating and cooling units excessively. A programmable thermostat helps you regulate the temperature of your home effectively, saving you energy and money. With a programmable thermostat, you can program your heating and cooling systems according to the activities you have planned during the day. 8 | 9 | For instance, when you're away from home, you can lower the thermostat settings to save energy. And when you're home, you can adjust the temperature to suit your comfort level and activities. An upgrade to a programmable thermostat is an efficient energy-saving solution worth investing in. 10 | 11 | 2. Replace Your Inefficient Bulbs 12 | 13 | Traditional incandescent bulbs waste a lot of energy which translates to high energy bills. The solution is to replace them with more efficient bulbs such as LED bulbs, CFLs, or halogen lights. These types of bulbs use only a fraction of the energy that incandescent bulbs use to produce the same amount of light. Additionally, LED bulbs can last up to 25 years, reducing further costs of regularly replacing your bulbs. 14 | 15 | 3. Use Energy-Efficient Appliances 16 | 17 | Using energy-efficient appliances is an excellent way to conserve energy and save money. When shopping for new appliances, consider purchasing those approved by the Energy Star program, which maintains stringent energy efficiency standards for household appliances. You can also save energy by choosing to replace your old appliances with eco-friendlier ones, such as energy-efficient washing machines, refrigerators, and ovens. 18 | 19 | 4. Go Solar 20 | 21 | Solar energy is becoming more attractive for homeowners seeking to save on energy bills while preserving the environment. Solar panel systems can help produce your electricity, hence lowering your dependency on the main power grid. Although solar panel installation might seem expensive at the beginning, the benefits of using a renewable energy source can definitely pay off in the long run. You can also claim tax incentives and sell excess power back to the grid, ultimately providing more cash in your pocket. 22 | 23 | 5. Seal Air Leaks 24 | 25 | Air leaks in your home can make your heating and cooling systems work harder, increasing your energy bills. Inspect your home regularly for air leaks in common areas such as doors, windows, vents, and ducts. If you find air leaks, use weather-stripping or caulking to cover the gaps effectively. In addition, you can seal large gaps with spray foam insulation, ensuring that cold or hot air does escape through any gaps in your walls. 26 | 27 | In conclusion, implementing these simple and affordable tips can help you reduce your energy bills, preserve the environment and help you live comfortably. To save money on energy bills, focus on energy-conserving measures like installing a programmable thermostat, replacing inefficient bulbs with energy-friendly ones, using energy-efficient appliances, going solar or sealing air leaks in your home. With these solutions, you can decrease your energy usage and save more money for other financial goals, all while living a comfortable and environmentally friendly lifestyle. -------------------------------------------------------------------------------- /outputs/post1_output.txt: -------------------------------------------------------------------------------- 1 | Title: Maximizing Your Savings: The Benefits of High Yield Savings Accounts and How to Choose the Best One in 2023 2 | 3 | Introduction 4 | 5 | When it comes to growing your savings, a high-yield savings account (HYSA) can be a valuable financial tool. In recent years, these accounts have gained popularity for their ability to provide higher returns than traditional savings accounts. In this blog post, we'll discuss the benefits of high-yield savings accounts and provide you with essential tips for choosing the best one in 2023. 6 | 7 | What Are High Yield Savings Accounts? 8 | 9 | A high-yield savings account is a type of deposit account offered by banks and credit unions that pays a higher interest rate compared to traditional savings accounts. They are designed to encourage people to save more money by offering a more attractive return on investment. 10 | 11 | Benefits of High Yield Savings Accounts 12 | 13 | Competitive Interest Rates: HYSAs typically offer higher interest rates than traditional savings accounts. This allows your money to grow at a faster rate and helps you reach your financial goals more quickly. 14 | 15 | Liquidity: Unlike other investment options, such as stocks or bonds, high-yield savings accounts offer easy access to your money. You can withdraw funds whenever you need them without penalties, making them ideal for emergency funds or short-term savings goals. 16 | 17 | Security: High-yield savings accounts are insured by the Federal Deposit Insurance Corporation (FDIC) or the National Credit Union Share Insurance Fund (NCUSIF), ensuring your money is safe and protected up to $250,000 per depositor, per institution. 18 | 19 | Low or No Fees: Many HYSAs have no monthly maintenance fees or minimum balance requirements, making them more affordable than other investment options. 20 | 21 | How to Choose the Best High Yield Savings Account in 2023 22 | 23 | Compare Interest Rates: Start by researching the available interest rates from different banks and credit unions. Online banks usually offer higher interest rates compared to brick-and-mortar institutions, as they have lower overhead costs. 24 | 25 | Look for Promotions: Some financial institutions offer promotional rates or bonuses for new customers. Be sure to factor in these promotions when comparing accounts, but also consider the long-term interest rates once the promotion ends. 26 | 27 | Consider Account Fees: Review the fees associated with each account, such as monthly maintenance fees, withdrawal fees, or minimum balance requirements. Look for an account with minimal or no fees to maximize your savings. 28 | 29 | Check Accessibility: Ensure that the financial institution offers user-friendly online and mobile banking options, as well as responsive customer support. 30 | 31 | Read Reviews: Look for online reviews and testimonials from customers who have used the high-yield savings accounts you're considering. This can give you valuable insight into their experiences and help you make an informed decision. 32 | 33 | Conclusion 34 | 35 | High-yield savings accounts can be an excellent way to grow your savings more quickly and achieve your financial goals. By considering factors such as interest rates, fees, accessibility, and customer reviews, you can find the best high-yield savings account for your needs in 2023. Start researching today and maximize the potential of your hard-earned money. -------------------------------------------------------------------------------- /outputs/post2_output.txt: -------------------------------------------------------------------------------- 1 | Title: Demystifying Short-Term Certificates of Deposit: A Beginner's Guide to Boosting Your Investment Portfolio 2 | 3 | Introduction 4 | 5 | If you're a beginner investor seeking a low-risk, relatively stable investment opportunity, look no further than short-term certificates of deposit (CDs). They offer a fixed interest rate over a specified period and are generally considered one of the safest options for new investors. In this blog post, we'll explore the ins and outs of short-term CDs, including their benefits, risks, and how they can fit into your investment portfolio. We'll also share tips for choosing the best short-term CDs and discuss current market trends to help you make informed decisions. 6 | 7 | What are Short-Term Certificates of Deposit? 8 | 9 | Certificates of deposit are time-bound savings accounts issued by banks and credit unions. When you invest in a CD, you're essentially loaning your money to the financial institution for a predetermined term, typically ranging from three months to five years. In return, the bank agrees to pay you interest at a fixed rate. 10 | 11 | Short-term CDs generally have terms between three months and one year. They're ideal for investors who want a relatively safe and conservative option for their money, without tying it up for an extended period. 12 | 13 | Benefits of Short-Term CDs 14 | 15 | Safety: Since CDs are insured by the Federal Deposit Insurance Corporation (FDIC) up to $250,000 per depositor, per insured bank, you can rest assured that your investment is secure. 16 | 17 | Predictable returns: Unlike stocks or other volatile investments, CDs provide a fixed interest rate over the agreed term, ensuring predictable returns. 18 | 19 | Flexibility: Short-term CDs enable you to access your funds sooner than long-term CDs, providing more flexibility in managing your investment portfolio. 20 | 21 | Low minimum investment: Many banks and credit unions offer CDs with a low minimum investment, making it easy for beginner investors to get started. 22 | 23 | Risks Associated with Short-Term CDs 24 | 25 | Limited returns: While short-term CDs are safe, their interest rates are typically lower than those of long-term CDs or other higher-risk investments. 26 | 27 | Inflation risk: In times of high inflation, the interest rate on a CD may not keep up with the rising cost of living, eroding the purchasing power of your investment. 28 | 29 | Early withdrawal penalties: Withdrawing your funds before the maturity date may result in penalties, reducing your overall return. 30 | 31 | Incorporating Short-Term CDs into Your Investment Portfolio 32 | 33 | Short-term CDs can be a valuable addition to your investment portfolio, particularly as a low-risk component. They're best suited for conservative investors or those looking to diversify their holdings. You can allocate a portion of your portfolio to short-term CDs, while investing the remainder in stocks, bonds, or other higher-yielding assets. This strategy can help you strike a balance between risk and return. 34 | 35 | Tips for Choosing the Best Short-Term CDs 36 | 37 | Compare interest rates: Shop around for the highest interest rates available from different banks and credit unions. Online comparison tools can help streamline this process. 38 | 39 | Review the term length: Choose a term that aligns with your financial goals and liquidity needs. If you think you might need access to your funds sooner, opt for shorter-term CDs. 40 | 41 | Look for promotional rates: Some institutions offer promotional rates on CDs for new customers or for a limited time. Take advantage of these promotions to boost your returns. 42 | 43 | Consider laddering: To maximize returns and maintain liquidity, create a CD ladder by investing in multiple CDs with staggered maturity dates. This strategy allows you to benefit from higher interest rates as your CDs mature and reinvest in new ones. 44 | 45 | Current Market Trends 46 | 47 | Interest rates have been relatively low in recent years, making it crucial to shop around for the best rates on short-term CDs. However, as the economy continues to recover, interest rates may start to rise, making short-term CDs more attractive to investors. Keep an eye on economic indicators and the Federal Reserve's actions, as they can influence CD rates in the short and long term. 48 | 49 | In addition, the rise of online banks and fintech companies has increased competition in the financial sector, which can lead to better CD rates and terms for consumers. Don't limit your search to traditional brick-and-mortar banks; consider exploring online banks and credit unions as well. 50 | 51 | Conclusion 52 | 53 | Short-term certificates of deposit can be a valuable addition to a beginner investor's portfolio, offering safety, predictability, and flexibility. By understanding the benefits and risks associated with short-term CDs and following our tips for choosing the best options, you can make informed decisions and bolster your investment strategy. Stay aware of current market trends and keep an eye on interest rates to ensure you're making the most of your short-term CD investments. 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "auto-gpt" 3 | version = "0.1.0" 4 | description = "A GPT based ai agent" 5 | readme = "README.md" 6 | 7 | [tool.black] 8 | line-length = 88 9 | target-version = ['py310'] 10 | include = '\.pyi?$' 11 | extend-exclude = "" -------------------------------------------------------------------------------- /requirements-docker.txt: -------------------------------------------------------------------------------- 1 | beautifulsoup4 2 | colorama==0.4.6 3 | openai==0.27.2 4 | playsound==1.2.2 5 | python-dotenv==1.0.0 6 | pyyaml==6.0 7 | readability-lxml==0.8.1 8 | requests 9 | tiktoken==0.3.3 10 | gTTS==2.3.1 11 | docker 12 | duckduckgo-search 13 | google-api-python-client #(https://developers.google.com/custom-search/v1/overview) 14 | pinecone-client==2.2.1 15 | redis 16 | orjson 17 | Pillow 18 | selenium 19 | webdriver-manager 20 | coverage 21 | flake8 22 | numpy 23 | pre-commit 24 | black 25 | isort 26 | gitpython==3.1.31 27 | tweepy -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | beautifulsoup4 2 | colorama==0.4.6 3 | openai==0.27.2 4 | playsound==1.2.2 5 | python-dotenv==1.0.0 6 | pyyaml==6.0 7 | readability-lxml==0.8.1 8 | requests 9 | tiktoken==0.3.3 10 | gTTS==2.3.1 11 | docker 12 | duckduckgo-search 13 | google-api-python-client #(https://developers.google.com/custom-search/v1/overview) 14 | pinecone-client==2.2.1 15 | redis 16 | orjson 17 | Pillow 18 | selenium 19 | webdriver-manager 20 | coverage 21 | flake8 22 | numpy 23 | pre-commit 24 | black 25 | sourcery 26 | isort 27 | gitpython==3.1.31 28 | pytest 29 | pytest-mock 30 | tweepy 31 | -------------------------------------------------------------------------------- /run.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | python scripts/check_requirements.py requirements.txt 3 | if errorlevel 1 ( 4 | echo Installing missing packages... 5 | pip install -r requirements.txt 6 | ) 7 | python -m autogpt %* 8 | pause 9 | -------------------------------------------------------------------------------- /run_continuous.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | set argument=--continuous 3 | call run.bat %argument% 4 | -------------------------------------------------------------------------------- /scripts/check_requirements.py: -------------------------------------------------------------------------------- 1 | import pkg_resources 2 | import sys 3 | 4 | 5 | def main(): 6 | requirements_file = sys.argv[1] 7 | with open(requirements_file, "r") as f: 8 | required_packages = [ 9 | line.strip().split("#")[0].strip() for line in f.readlines() 10 | ] 11 | 12 | installed_packages = [package.key for package in pkg_resources.working_set] 13 | 14 | missing_packages = [] 15 | for package in required_packages: 16 | if not package: # Skip empty lines 17 | continue 18 | package_name = package.strip().split("==")[0] 19 | if package_name.lower() not in installed_packages: 20 | missing_packages.append(package_name) 21 | 22 | if missing_packages: 23 | print("Missing packages:") 24 | print(", ".join(missing_packages)) 25 | sys.exit(1) 26 | else: 27 | print("All packages are installed.") 28 | 29 | 30 | if __name__ == "__main__": 31 | main() 32 | -------------------------------------------------------------------------------- /scripts/execute_code.py: -------------------------------------------------------------------------------- 1 | import docker 2 | import os 3 | import subprocess 4 | 5 | 6 | WORKSPACE_FOLDER = "auto_gpt_workspace" 7 | 8 | 9 | def execute_python_file(file): 10 | """执行一个 Python 文件在 Docker 容器中,并返回输出""" 11 | 12 | print (f"正在工作空间 '{WORKSPACE_FOLDER}' 中执行文件 '{file}'") 13 | 14 | if not file.endswith(".py"): 15 | return "Error: 无效的文件类型。仅允许 .py 文件." 16 | 17 | file_path = os.path.join(WORKSPACE_FOLDER, file) 18 | 19 | if not os.path.isfile(file_path): 20 | return f"Error: 文件 '{file}' 不存在." 21 | 22 | try: 23 | client = docker.from_env() 24 | 25 | image_name = 'python:3.10' 26 | try: 27 | client.images.get(image_name) 28 | print(f"Image '{image_name}' found locally") 29 | except docker.errors.ImageNotFound: 30 | print(f"Image '{image_name}' not found locally, pulling from Docker Hub") 31 | # Use the low-level API to stream the pull response 32 | low_level_client = docker.APIClient() 33 | for line in low_level_client.pull(image_name, stream=True, decode=True): 34 | # Print the status and progress, if available 35 | status = line.get('status') 36 | progress = line.get('progress') 37 | if status and progress: 38 | print(f"{status}: {progress}") 39 | elif status: 40 | print(status) 41 | 42 | # You can replace 'python:3.8' with the desired Python image/version 43 | # You can find available Python images on Docker Hub: 44 | # https://hub.docker.com/_/python 45 | container = client.containers.run( 46 | image_name, 47 | f'python {file}', 48 | volumes={ 49 | os.path.abspath(WORKSPACE_FOLDER): { 50 | 'bind': '/workspace', 51 | 'mode': 'ro'}}, 52 | working_dir='/workspace', 53 | stderr=True, 54 | stdout=True, 55 | detach=True, 56 | ) 57 | 58 | output = container.wait() 59 | logs = container.logs().decode('utf-8') 60 | container.remove() 61 | 62 | # print(f"Execution complete. Output: {output}") 63 | # print(f"Logs: {logs}") 64 | 65 | return logs 66 | 67 | except Exception as e: 68 | return f"Error: {str(e)}" 69 | 70 | 71 | def execute_shell(command_line): 72 | 73 | current_dir = os.getcwd() 74 | 75 | if not WORKSPACE_FOLDER in current_dir: # Change dir into workspace if necessary 76 | work_dir = os.path.join(os.getcwd(), WORKSPACE_FOLDER) 77 | os.chdir(work_dir) 78 | 79 | print (f"Executing command '{command_line}' in working directory '{os.getcwd()}'") 80 | 81 | result = subprocess.run(command_line, capture_output=True, shell=True) 82 | output = f"STDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}" 83 | 84 | # Change back to whatever the prior working dir was 85 | 86 | os.chdir(current_dir) 87 | 88 | return output 89 | -------------------------------------------------------------------------------- /scripts/file_operations.py: -------------------------------------------------------------------------------- 1 | import os 2 | import os.path 3 | 4 | # Set a dedicated folder for file I/O 5 | working_directory = "auto_gpt_workspace" 6 | 7 | # Create the directory if it doesn't exist 8 | if not os.path.exists(working_directory): 9 | os.makedirs(working_directory) 10 | 11 | 12 | def safe_join(base, *paths): 13 | """智能连接一个或多个路径组件。""" 14 | new_path = os.path.join(base, *paths) 15 | norm_new_path = os.path.normpath(new_path) 16 | 17 | if os.path.commonprefix([base, norm_new_path]) != base: 18 | raise ValueError("尝试访问工作目录之外的位置。") 19 | 20 | return norm_new_path 21 | 22 | 23 | def read_file(filename): 24 | """读取文件并返回内容""" 25 | try: 26 | filepath = safe_join(working_directory, filename) 27 | with open(filepath, "r", encoding='utf-8') as f: 28 | content = f.read() 29 | return content 30 | except Exception as e: 31 | return "Error: " + str(e) 32 | 33 | 34 | def write_to_file(filename, text): 35 | """将文本写入文件""" 36 | try: 37 | filepath = safe_join(working_directory, filename) 38 | directory = os.path.dirname(filepath) 39 | if not os.path.exists(directory): 40 | os.makedirs(directory) 41 | with open(filepath, "w", encoding='utf-8') as f: 42 | f.write(text) 43 | return "文件写入成功。" 44 | except Exception as e: 45 | return "Error: " + str(e) 46 | 47 | 48 | def append_to_file(filename, text): 49 | """将文本追加到文件""" 50 | try: 51 | filepath = safe_join(working_directory, filename) 52 | with open(filepath, "a") as f: 53 | f.write(text) 54 | return "已成功添加文本." 55 | except Exception as e: 56 | return "Error: " + str(e) 57 | 58 | 59 | def delete_file(filename): 60 | """删除文件""" 61 | try: 62 | filepath = safe_join(working_directory, filename) 63 | os.remove(filepath) 64 | return "文件删除成功." 65 | except Exception as e: 66 | return "Error: " + str(e) 67 | 68 | 69 | def search_files(directory): 70 | found_files = [] 71 | 72 | if directory == "" or directory == "/": 73 | search_directory = working_directory 74 | else: 75 | search_directory = safe_join(working_directory, directory) 76 | 77 | for root, _, files in os.walk(search_directory): 78 | for file in files: 79 | if file.startswith('.'): 80 | continue 81 | relative_path = os.path.relpath(os.path.join(root, file), working_directory) 82 | found_files.append(relative_path) 83 | 84 | return found_files 85 | -------------------------------------------------------------------------------- /scripts/main.py: -------------------------------------------------------------------------------- 1 | from colorama import Style, init 2 | 3 | # Initialize colorama 4 | init(autoreset=True) 5 | 6 | # Use the bold ANSI style 7 | print( 8 | f"""{Style.BRIGHT}请 运行: 9 | python -m autogpt 10 | """ 11 | ) 12 | -------------------------------------------------------------------------------- /scripts/prompt.py: -------------------------------------------------------------------------------- 1 | from promptgenerator import PromptGenerator 2 | 3 | 4 | def get_prompt(): 5 | """ 6 | 此函数生成包含各种约束、命令、资源和性能评估的提示字符串。 7 | 返回: 8 | str: 生成的提示字符串。 9 | """ 10 | 11 | # Initialize the PromptGenerator object 12 | prompt_generator = PromptGenerator() 13 | 14 | # Add constraints to the PromptGenerator object 15 | prompt_generator.add_constraint("~4000 word limit for short term memory. Your short term memory is short, so immediately save important information to files.") 16 | prompt_generator.add_constraint("If you are unsure how you previously did something or want to recall past events, thinking about similar events will help you remember.") 17 | prompt_generator.add_constraint("No user assistance") 18 | prompt_generator.add_constraint("Reply in Chinese") 19 | prompt_generator.add_constraint('Exclusively use the commands listed in double quotes e.g. "command name"') 20 | 21 | 22 | # Define the command list 23 | commands = [ 24 | ("Google Search", "google", {"input": ""}), 25 | ("Browse Website", "browse_website", {"url": "", "question": ""}), 26 | ("Start GPT Agent", "start_agent", {"name": "", "task": "", "prompt": ""}), 27 | ("Message GPT Agent", "message_agent", {"key": "", "message": ""}), 28 | ("List GPT Agents", "list_agents", {}), 29 | ("Delete GPT Agent", "delete_agent", {"key": ""}), 30 | ("Write to file", "write_to_file", {"file": "", "text": ""}), 31 | ("Read file", "read_file", {"file": ""}), 32 | ("Append to file", "append_to_file", {"file": "", "text": ""}), 33 | ("Delete file", "delete_file", {"file": ""}), 34 | ("Search Files", "search_files", {"directory": ""}), 35 | ("Evaluate Code", "evaluate_code", {"code": ""}), 36 | ("Get Improved Code", "improve_code", {"suggestions": "", "code": ""}), 37 | ("Write Tests", "write_tests", {"code": "", "focus": ""}), 38 | ("Execute Python File", "execute_python_file", {"file": ""}), 39 | ("Execute Shell Command, non-interactive commands only", "execute_shell", { "command_line": ""}), 40 | ("Task Complete (Shutdown)", "task_complete", {"reason": ""}), 41 | ("Generate Image", "generate_image", {"prompt": ""}), 42 | ("Do Nothing", "do_nothing", {}), 43 | ] 44 | 45 | # Add commands to the PromptGenerator object 46 | for command_label, command_name, args in commands: 47 | prompt_generator.add_command(command_label, command_name, args) 48 | 49 | # Add resources to the PromptGenerator object 50 | prompt_generator.add_resource("Internet access for searches and information gathering.") 51 | prompt_generator.add_resource("Long Term memory management.") 52 | prompt_generator.add_resource("GPT-3.5 powered Agents for delegation of simple tasks.") 53 | prompt_generator.add_resource("File output.") 54 | 55 | # Add performance evaluations to the PromptGenerator object 56 | prompt_generator.add_performance_evaluation("Continuously review and analyze your actions to ensure you are performing to the best of your abilities.") 57 | prompt_generator.add_performance_evaluation("Constructively self-criticize your big-picture behavior constantly.") 58 | prompt_generator.add_performance_evaluation("Reflect on past decisions and strategies to refine your approach.") 59 | prompt_generator.add_performance_evaluation("Every command has a cost, so be smart and efficient. Aim to complete tasks in the least number of steps.") 60 | 61 | # Generate the prompt string 62 | prompt_string = prompt_generator.generate_prompt_string() 63 | 64 | return prompt_string 65 | -------------------------------------------------------------------------------- /tests.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import coverage 3 | 4 | if __name__ == "__main__": 5 | # Start coverage collection 6 | cov = coverage.Coverage() 7 | cov.start() 8 | 9 | # Load all tests from the 'autogpt/tests' package 10 | suite = unittest.defaultTestLoader.discover("./tests") 11 | 12 | # Run the tests 13 | unittest.TextTestRunner().run(suite) 14 | 15 | # Stop coverage collection 16 | cov.stop() 17 | cov.save() 18 | 19 | # Report the coverage 20 | cov.report(show_missing=True) 21 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaqijiang/Auto-GPT-aj/310a84c8ca0173c7db43f637866cf5677bd7ef50/tests/__init__.py -------------------------------------------------------------------------------- /tests/browse_tests.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import os 3 | import sys 4 | 5 | from bs4 import BeautifulSoup 6 | 7 | sys.path.append(os.path.abspath("../scripts")) 8 | 9 | from browse import extract_hyperlinks 10 | 11 | 12 | class TestBrowseLinks(unittest.TestCase): 13 | def test_extract_hyperlinks(self): 14 | body = """ 15 | 16 | Google 17 | Foo 18 |
Some other crap
19 | 20 | """ 21 | soup = BeautifulSoup(body, "html.parser") 22 | links = extract_hyperlinks(soup, "http://example.com") 23 | self.assertEqual( 24 | links, 25 | [("Google", "https://google.com"), ("Foo", "http://example.com/foo.html")], 26 | ) 27 | -------------------------------------------------------------------------------- /tests/context.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | sys.path.insert( 5 | 0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../scripts")) 6 | ) 7 | -------------------------------------------------------------------------------- /tests/integration/memory_tests.py: -------------------------------------------------------------------------------- 1 | import random 2 | import string 3 | import sys 4 | import unittest 5 | from pathlib import Path 6 | 7 | from autogpt.config import Config 8 | from autogpt.memory.local import LocalCache 9 | 10 | 11 | class TestLocalCache(unittest.TestCase): 12 | def random_string(self, length): 13 | return "".join(random.choice(string.ascii_letters) for _ in range(length)) 14 | 15 | def setUp(self): 16 | cfg = cfg = Config() 17 | self.cache = LocalCache(cfg) 18 | self.cache.clear() 19 | 20 | # Add example texts to the cache 21 | self.example_texts = [ 22 | "The quick brown fox jumps over the lazy dog", 23 | "I love machine learning and natural language processing", 24 | "The cake is a lie, but the pie is always true", 25 | "ChatGPT is an advanced AI model for conversation", 26 | ] 27 | 28 | for text in self.example_texts: 29 | self.cache.add(text) 30 | 31 | # Add some random strings to test noise 32 | for _ in range(5): 33 | self.cache.add(self.random_string(10)) 34 | 35 | def test_get_relevant(self): 36 | query = "I'm interested in artificial intelligence and NLP" 37 | k = 3 38 | relevant_texts = self.cache.get_relevant(query, k) 39 | 40 | print(f"Top {k} relevant texts for the query '{query}':") 41 | for i, text in enumerate(relevant_texts, start=1): 42 | print(f"{i}. {text}") 43 | 44 | self.assertEqual(len(relevant_texts), k) 45 | self.assertIn(self.example_texts[1], relevant_texts) 46 | 47 | 48 | if __name__ == "__main__": 49 | unittest.main() 50 | -------------------------------------------------------------------------------- /tests/integration/milvus_memory_tests.py: -------------------------------------------------------------------------------- 1 | import random 2 | import string 3 | import unittest 4 | 5 | from autogpt.config import Config 6 | from autogpt.memory.milvus import MilvusMemory 7 | 8 | 9 | class TestMilvusMemory(unittest.TestCase): 10 | def random_string(self, length): 11 | return "".join(random.choice(string.ascii_letters) for _ in range(length)) 12 | 13 | def setUp(self): 14 | cfg = Config() 15 | cfg.milvus_addr = "localhost:19530" 16 | self.memory = MilvusMemory(cfg) 17 | self.memory.clear() 18 | 19 | # Add example texts to the cache 20 | self.example_texts = [ 21 | "The quick brown fox jumps over the lazy dog", 22 | "I love machine learning and natural language processing", 23 | "The cake is a lie, but the pie is always true", 24 | "ChatGPT is an advanced AI model for conversation", 25 | ] 26 | 27 | for text in self.example_texts: 28 | self.memory.add(text) 29 | 30 | # Add some random strings to test noise 31 | for _ in range(5): 32 | self.memory.add(self.random_string(10)) 33 | 34 | def test_get_relevant(self): 35 | query = "I'm interested in artificial intelligence and NLP" 36 | k = 3 37 | relevant_texts = self.memory.get_relevant(query, k) 38 | 39 | print(f"Top {k} relevant texts for the query '{query}':") 40 | for i, text in enumerate(relevant_texts, start=1): 41 | print(f"{i}. {text}") 42 | 43 | self.assertEqual(len(relevant_texts), k) 44 | self.assertIn(self.example_texts[1], relevant_texts) 45 | 46 | 47 | if __name__ == "__main__": 48 | unittest.main() 49 | -------------------------------------------------------------------------------- /tests/integration/weaviate_memory_tests.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from unittest import mock 3 | import sys 4 | import os 5 | 6 | from weaviate import Client 7 | from weaviate.util import get_valid_uuid 8 | from uuid import uuid4 9 | 10 | from autogpt.config import Config 11 | from autogpt.memory.weaviate import WeaviateMemory 12 | from autogpt.memory.base import get_ada_embedding 13 | 14 | 15 | @mock.patch.dict(os.environ, { 16 | "WEAVIATE_HOST": "127.0.0.1", 17 | "WEAVIATE_PROTOCOL": "http", 18 | "WEAVIATE_PORT": "8080", 19 | "WEAVIATE_USERNAME": "", 20 | "WEAVIATE_PASSWORD": "", 21 | "MEMORY_INDEX": "AutogptTests" 22 | }) 23 | class TestWeaviateMemory(unittest.TestCase): 24 | cfg = None 25 | client = None 26 | 27 | @classmethod 28 | def setUpClass(cls): 29 | # only create the connection to weaviate once 30 | cls.cfg = Config() 31 | 32 | if cls.cfg.use_weaviate_embedded: 33 | from weaviate.embedded import EmbeddedOptions 34 | 35 | cls.client = Client(embedded_options=EmbeddedOptions( 36 | hostname=cls.cfg.weaviate_host, 37 | port=int(cls.cfg.weaviate_port), 38 | persistence_data_path=cls.cfg.weaviate_embedded_path 39 | )) 40 | else: 41 | cls.client = Client(f"{cls.cfg.weaviate_protocol}://{cls.cfg.weaviate_host}:{self.cfg.weaviate_port}") 42 | 43 | """ 44 | In order to run these tests you will need a local instance of 45 | Weaviate running. Refer to https://weaviate.io/developers/weaviate/installation/docker-compose 46 | for creating local instances using docker. 47 | Alternatively in your .env file set the following environmental variables to run Weaviate embedded (see: https://weaviate.io/developers/weaviate/installation/embedded): 48 | 49 | USE_WEAVIATE_EMBEDDED=True 50 | WEAVIATE_EMBEDDED_PATH="/home/me/.local/share/weaviate" 51 | """ 52 | def setUp(self): 53 | try: 54 | self.client.schema.delete_class(self.cfg.memory_index) 55 | except: 56 | pass 57 | 58 | self.memory = WeaviateMemory(self.cfg) 59 | 60 | def test_add(self): 61 | doc = 'You are a Titan name Thanos and you are looking for the Infinity Stones' 62 | self.memory.add(doc) 63 | result = self.client.query.get(self.cfg.memory_index, ['raw_text']).do() 64 | actual = result['data']['Get'][self.cfg.memory_index] 65 | 66 | self.assertEqual(len(actual), 1) 67 | self.assertEqual(actual[0]['raw_text'], doc) 68 | 69 | def test_get(self): 70 | doc = 'You are an Avenger and swore to defend the Galaxy from a menace called Thanos' 71 | 72 | with self.client.batch as batch: 73 | batch.add_data_object( 74 | uuid=get_valid_uuid(uuid4()), 75 | data_object={'raw_text': doc}, 76 | class_name=self.cfg.memory_index, 77 | vector=get_ada_embedding(doc) 78 | ) 79 | 80 | batch.flush() 81 | 82 | actual = self.memory.get(doc) 83 | 84 | self.assertEqual(len(actual), 1) 85 | self.assertEqual(actual[0], doc) 86 | 87 | def test_get_stats(self): 88 | docs = [ 89 | 'You are now about to count the number of docs in this index', 90 | 'And then you about to find out if you can count correctly' 91 | ] 92 | 93 | [self.memory.add(doc) for doc in docs] 94 | 95 | stats = self.memory.get_stats() 96 | 97 | self.assertTrue(stats) 98 | self.assertTrue('count' in stats) 99 | self.assertEqual(stats['count'], 2) 100 | 101 | def test_clear(self): 102 | docs = [ 103 | 'Shame this is the last test for this class', 104 | 'Testing is fun when someone else is doing it' 105 | ] 106 | 107 | [self.memory.add(doc) for doc in docs] 108 | 109 | self.assertEqual(self.memory.get_stats()['count'], 2) 110 | 111 | self.memory.clear() 112 | 113 | self.assertEqual(self.memory.get_stats()['count'], 0) 114 | 115 | 116 | if __name__ == '__main__': 117 | unittest.main() 118 | -------------------------------------------------------------------------------- /tests/local_cache_test.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import unittest 4 | 5 | from autogpt.memory.local import LocalCache 6 | 7 | 8 | def MockConfig(): 9 | return type( 10 | "MockConfig", 11 | (object,), 12 | { 13 | "debug_mode": False, 14 | "continuous_mode": False, 15 | "speak_mode": False, 16 | "memory_index": "auto-gpt", 17 | }, 18 | ) 19 | 20 | 21 | class TestLocalCache(unittest.TestCase): 22 | def setUp(self): 23 | self.cfg = MockConfig() 24 | self.cache = LocalCache(self.cfg) 25 | 26 | def test_add(self): 27 | text = "Sample text" 28 | self.cache.add(text) 29 | self.assertIn(text, self.cache.data.texts) 30 | 31 | def test_clear(self): 32 | self.cache.clear() 33 | self.assertEqual(self.cache.data, [""]) 34 | 35 | def test_get(self): 36 | text = "Sample text" 37 | self.cache.add(text) 38 | result = self.cache.get(text) 39 | self.assertEqual(result, [text]) 40 | 41 | def test_get_relevant(self): 42 | text1 = "Sample text 1" 43 | text2 = "Sample text 2" 44 | self.cache.add(text1) 45 | self.cache.add(text2) 46 | result = self.cache.get_relevant(text1, 1) 47 | self.assertEqual(result, [text1]) 48 | 49 | def test_get_stats(self): 50 | text = "Sample text" 51 | self.cache.add(text) 52 | stats = self.cache.get_stats() 53 | self.assertEqual(stats, (1, self.cache.data.embeddings.shape)) 54 | 55 | 56 | if __name__ == "__main__": 57 | unittest.main() 58 | -------------------------------------------------------------------------------- /tests/milvus_memory_test.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import unittest 4 | 5 | from autogpt.memory.milvus import MilvusMemory 6 | 7 | 8 | def MockConfig(): 9 | return type( 10 | "MockConfig", 11 | (object,), 12 | { 13 | "debug_mode": False, 14 | "continuous_mode": False, 15 | "speak_mode": False, 16 | "milvus_collection": "autogpt", 17 | "milvus_addr": "localhost:19530", 18 | }, 19 | ) 20 | 21 | 22 | class TestMilvusMemory(unittest.TestCase): 23 | def setUp(self): 24 | self.cfg = MockConfig() 25 | self.memory = MilvusMemory(self.cfg) 26 | 27 | def test_add(self): 28 | text = "Sample text" 29 | self.memory.clear() 30 | self.memory.add(text) 31 | result = self.memory.get(text) 32 | self.assertEqual([text], result) 33 | 34 | def test_clear(self): 35 | self.memory.clear() 36 | self.assertEqual(self.memory.collection.num_entities, 0) 37 | 38 | def test_get(self): 39 | text = "Sample text" 40 | self.memory.clear() 41 | self.memory.add(text) 42 | result = self.memory.get(text) 43 | self.assertEqual(result, [text]) 44 | 45 | def test_get_relevant(self): 46 | text1 = "Sample text 1" 47 | text2 = "Sample text 2" 48 | self.memory.clear() 49 | self.memory.add(text1) 50 | self.memory.add(text2) 51 | result = self.memory.get_relevant(text1, 1) 52 | self.assertEqual(result, [text1]) 53 | 54 | def test_get_stats(self): 55 | text = "Sample text" 56 | self.memory.clear() 57 | self.memory.add(text) 58 | stats = self.memory.get_stats() 59 | self.assertEqual(15, len(stats)) 60 | 61 | 62 | if __name__ == "__main__": 63 | unittest.main() 64 | -------------------------------------------------------------------------------- /tests/smoke_test.py: -------------------------------------------------------------------------------- 1 | import os 2 | import subprocess 3 | import sys 4 | import unittest 5 | 6 | from autogpt.commands.file_operations import delete_file, read_file 7 | 8 | env_vars = {"MEMORY_BACKEND": "no_memory", "TEMPERATURE": "0"} 9 | 10 | 11 | class TestCommands(unittest.TestCase): 12 | def test_write_file(self): 13 | # Test case to check if the write_file command can successfully write 'Hello World' to a file 14 | # named 'hello_world.txt'. 15 | 16 | # Read the current ai_settings.yaml file and store its content. 17 | ai_settings = None 18 | if os.path.exists("ai_settings.yaml"): 19 | with open("ai_settings.yaml", "r") as f: 20 | ai_settings = f.read() 21 | os.remove("ai_settings.yaml") 22 | 23 | try: 24 | if os.path.exists("hello_world.txt"): 25 | # Clean up any existing 'hello_world.txt' file before testing. 26 | delete_file("hello_world.txt") 27 | # Prepare input data for the test. 28 | input_data = """write_file-GPT 29 | an AI designed to use the write_file command to write 'Hello World' into a file named "hello_world.txt" and then use the task_complete command to complete the task. 30 | Use the write_file command to write 'Hello World' into a file named "hello_world.txt". 31 | Use the task_complete command to complete the task. 32 | Do not use any other commands. 33 | 34 | y -5 35 | EOF""" 36 | command = f"{sys.executable} -m autogpt" 37 | 38 | # Execute the script with the input data. 39 | process = subprocess.Popen( 40 | command, 41 | stdin=subprocess.PIPE, 42 | shell=True, 43 | env={**os.environ, **env_vars}, 44 | ) 45 | process.communicate(input_data.encode()) 46 | 47 | # Read the content of the 'hello_world.txt' file created during the test. 48 | content = read_file("hello_world.txt") 49 | finally: 50 | if ai_settings: 51 | # Restore the original ai_settings.yaml file. 52 | with open("ai_settings.yaml", "w") as f: 53 | f.write(ai_settings) 54 | 55 | # Check if the content of the 'hello_world.txt' file is equal to 'Hello World'. 56 | self.assertEqual( 57 | content, "Hello World", f"Expected 'Hello World', got {content}" 58 | ) 59 | 60 | 61 | # Run the test case. 62 | if __name__ == "__main__": 63 | unittest.main() 64 | -------------------------------------------------------------------------------- /tests/test_config.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | 3 | from autogpt.config import Config 4 | 5 | 6 | class TestConfig(TestCase): 7 | """ 8 | Test cases for the Config class, which handles the configuration settings 9 | for the AI and ensures it behaves as a singleton. 10 | """ 11 | 12 | def setUp(self): 13 | """ 14 | Set up the test environment by creating an instance of the Config class. 15 | """ 16 | self.config = Config() 17 | 18 | def test_singleton(self): 19 | """ 20 | Test if the Config class behaves as a singleton by ensuring that two instances are the same. 21 | """ 22 | config2 = Config() 23 | self.assertIs(self.config, config2) 24 | 25 | def test_initial_values(self): 26 | """ 27 | Test if the initial values of the Config class attributes are set correctly. 28 | """ 29 | self.assertFalse(self.config.debug_mode) 30 | self.assertFalse(self.config.continuous_mode) 31 | self.assertFalse(self.config.speak_mode) 32 | self.assertEqual(self.config.fast_llm_model, "gpt-3.5-turbo") 33 | self.assertEqual(self.config.smart_llm_model, "gpt-4") 34 | self.assertEqual(self.config.fast_token_limit, 4000) 35 | self.assertEqual(self.config.smart_token_limit, 8000) 36 | 37 | def test_set_continuous_mode(self): 38 | """ 39 | Test if the set_continuous_mode() method updates the continuous_mode attribute. 40 | """ 41 | self.config.set_continuous_mode(True) 42 | self.assertTrue(self.config.continuous_mode) 43 | 44 | def test_set_speak_mode(self): 45 | """ 46 | Test if the set_speak_mode() method updates the speak_mode attribute. 47 | """ 48 | self.config.set_speak_mode(True) 49 | self.assertTrue(self.config.speak_mode) 50 | 51 | def test_set_fast_llm_model(self): 52 | """ 53 | Test if the set_fast_llm_model() method updates the fast_llm_model attribute. 54 | """ 55 | self.config.set_fast_llm_model("gpt-3.5-turbo-test") 56 | self.assertEqual(self.config.fast_llm_model, "gpt-3.5-turbo-test") 57 | 58 | def test_set_smart_llm_model(self): 59 | """ 60 | Test if the set_smart_llm_model() method updates the smart_llm_model attribute. 61 | """ 62 | self.config.set_smart_llm_model("gpt-4-test") 63 | self.assertEqual(self.config.smart_llm_model, "gpt-4-test") 64 | 65 | def test_set_fast_token_limit(self): 66 | """ 67 | Test if the set_fast_token_limit() method updates the fast_token_limit attribute. 68 | """ 69 | self.config.set_fast_token_limit(5000) 70 | self.assertEqual(self.config.fast_token_limit, 5000) 71 | 72 | def test_set_smart_token_limit(self): 73 | """ 74 | Test if the set_smart_token_limit() method updates the smart_token_limit attribute. 75 | """ 76 | self.config.set_smart_token_limit(9000) 77 | self.assertEqual(self.config.smart_token_limit, 9000) 78 | 79 | def test_set_debug_mode(self): 80 | """ 81 | Test if the set_debug_mode() method updates the debug_mode attribute. 82 | """ 83 | self.config.set_debug_mode(True) 84 | self.assertTrue(self.config.debug_mode) 85 | -------------------------------------------------------------------------------- /tests/test_prompt_generator.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | 3 | from autogpt.promptgenerator import PromptGenerator 4 | 5 | 6 | class TestPromptGenerator(TestCase): 7 | """ 8 | Test cases for the PromptGenerator class, which is responsible for generating 9 | prompts for the AI with constraints, commands, resources, and performance evaluations. 10 | """ 11 | 12 | @classmethod 13 | def setUpClass(cls): 14 | """ 15 | Set up the initial state for each test method by creating an instance of PromptGenerator. 16 | """ 17 | cls.generator = PromptGenerator() 18 | 19 | # Test whether the add_constraint() method adds a constraint to the generator's constraints list 20 | def test_add_constraint(self): 21 | """ 22 | Test if the add_constraint() method adds a constraint to the generator's constraints list. 23 | """ 24 | constraint = "Constraint1" 25 | self.generator.add_constraint(constraint) 26 | self.assertIn(constraint, self.generator.constraints) 27 | 28 | # Test whether the add_command() method adds a command to the generator's commands list 29 | def test_add_command(self): 30 | """ 31 | Test if the add_command() method adds a command to the generator's commands list. 32 | """ 33 | command_label = "Command Label" 34 | command_name = "command_name" 35 | args = {"arg1": "value1", "arg2": "value2"} 36 | self.generator.add_command(command_label, command_name, args) 37 | command = { 38 | "label": command_label, 39 | "name": command_name, 40 | "args": args, 41 | } 42 | self.assertIn(command, self.generator.commands) 43 | 44 | def test_add_resource(self): 45 | """ 46 | Test if the add_resource() method adds a resource to the generator's resources list. 47 | """ 48 | resource = "Resource1" 49 | self.generator.add_resource(resource) 50 | self.assertIn(resource, self.generator.resources) 51 | 52 | def test_add_performance_evaluation(self): 53 | """ 54 | Test if the add_performance_evaluation() method adds an evaluation to the generator's 55 | performance_evaluation list. 56 | """ 57 | evaluation = "Evaluation1" 58 | self.generator.add_performance_evaluation(evaluation) 59 | self.assertIn(evaluation, self.generator.performance_evaluation) 60 | 61 | def test_generate_prompt_string(self): 62 | """ 63 | Test if the generate_prompt_string() method generates a prompt string with all the added 64 | constraints, commands, resources, and evaluations. 65 | """ 66 | # Define the test data 67 | constraints = ["Constraint1", "Constraint2"] 68 | commands = [ 69 | { 70 | "label": "Command1", 71 | "name": "command_name1", 72 | "args": {"arg1": "value1"}, 73 | }, 74 | { 75 | "label": "Command2", 76 | "name": "command_name2", 77 | "args": {}, 78 | }, 79 | ] 80 | resources = ["Resource1", "Resource2"] 81 | evaluations = ["Evaluation1", "Evaluation2"] 82 | 83 | # Add test data to the generator 84 | for constraint in constraints: 85 | self.generator.add_constraint(constraint) 86 | for command in commands: 87 | self.generator.add_command( 88 | command["label"], command["name"], command["args"] 89 | ) 90 | for resource in resources: 91 | self.generator.add_resource(resource) 92 | for evaluation in evaluations: 93 | self.generator.add_performance_evaluation(evaluation) 94 | 95 | # Generate the prompt string and verify its correctness 96 | prompt_string = self.generator.generate_prompt_string() 97 | self.assertIsNotNone(prompt_string) 98 | 99 | # Check if all constraints, commands, resources, and evaluations are present in the prompt string 100 | for constraint in constraints: 101 | self.assertIn(constraint, prompt_string) 102 | for command in commands: 103 | self.assertIn(command["name"], prompt_string) 104 | for key, value in command["args"].items(): 105 | self.assertIn(f'"{key}": "{value}"', prompt_string) 106 | for resource in resources: 107 | self.assertIn(resource, prompt_string) 108 | for evaluation in evaluations: 109 | self.assertIn(evaluation, prompt_string) 110 | 111 | self.assertIn("constraints", prompt_string.lower()) 112 | self.assertIn("commands", prompt_string.lower()) 113 | self.assertIn("resources", prompt_string.lower()) 114 | self.assertIn("performance evaluation", prompt_string.lower()) 115 | -------------------------------------------------------------------------------- /tests/test_token_counter.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import tests.context 3 | from autogpt.token_counter import count_message_tokens, count_string_tokens 4 | 5 | 6 | class TestTokenCounter(unittest.TestCase): 7 | def test_count_message_tokens(self): 8 | messages = [ 9 | {"role": "user", "content": "Hello"}, 10 | {"role": "assistant", "content": "Hi there!"}, 11 | ] 12 | self.assertEqual(count_message_tokens(messages), 17) 13 | 14 | def test_count_message_tokens_with_name(self): 15 | messages = [ 16 | {"role": "user", "content": "Hello", "name": "John"}, 17 | {"role": "assistant", "content": "Hi there!"}, 18 | ] 19 | self.assertEqual(count_message_tokens(messages), 17) 20 | 21 | def test_count_message_tokens_empty_input(self): 22 | self.assertEqual(count_message_tokens([]), 3) 23 | 24 | def test_count_message_tokens_invalid_model(self): 25 | messages = [ 26 | {"role": "user", "content": "Hello"}, 27 | {"role": "assistant", "content": "Hi there!"}, 28 | ] 29 | with self.assertRaises(KeyError): 30 | count_message_tokens(messages, model="invalid_model") 31 | 32 | def test_count_message_tokens_gpt_4(self): 33 | messages = [ 34 | {"role": "user", "content": "Hello"}, 35 | {"role": "assistant", "content": "Hi there!"}, 36 | ] 37 | self.assertEqual(count_message_tokens(messages, model="gpt-4-0314"), 15) 38 | 39 | def test_count_string_tokens(self): 40 | string = "Hello, world!" 41 | self.assertEqual( 42 | count_string_tokens(string, model_name="gpt-3.5-turbo-0301"), 4 43 | ) 44 | 45 | def test_count_string_tokens_empty_input(self): 46 | self.assertEqual(count_string_tokens("", model_name="gpt-3.5-turbo-0301"), 0) 47 | 48 | def test_count_message_tokens_invalid_model(self): 49 | messages = [ 50 | {"role": "user", "content": "Hello"}, 51 | {"role": "assistant", "content": "Hi there!"}, 52 | ] 53 | with self.assertRaises(NotImplementedError): 54 | count_message_tokens(messages, model="invalid_model") 55 | 56 | def test_count_string_tokens_gpt_4(self): 57 | string = "Hello, world!" 58 | self.assertEqual(count_string_tokens(string, model_name="gpt-4-0314"), 4) 59 | 60 | 61 | if __name__ == "__main__": 62 | unittest.main() 63 | -------------------------------------------------------------------------------- /tests/unit/test_browse_scrape_text.py: -------------------------------------------------------------------------------- 1 | # Generated by CodiumAI 2 | 3 | import requests 4 | 5 | from autogpt.commands.web_requests import scrape_text 6 | 7 | """ 8 | Code Analysis 9 | 10 | Objective: 11 | The objective of the "scrape_text" function is to scrape the text content from 12 | a given URL and return it as a string, after removing any unwanted HTML tags and scripts. 13 | 14 | Inputs: 15 | - url: a string representing the URL of the webpage to be scraped. 16 | 17 | Flow: 18 | 1. Send a GET request to the given URL using the requests library and the user agent header from the config file. 19 | 2. Check if the response contains an HTTP error. If it does, return an error message. 20 | 3. Use BeautifulSoup to parse the HTML content of the response and extract all script and style tags. 21 | 4. Get the text content of the remaining HTML using the get_text() method of BeautifulSoup. 22 | 5. Split the text into lines and then into chunks, removing any extra whitespace. 23 | 6. Join the chunks into a single string with newline characters between them. 24 | 7. Return the cleaned text. 25 | 26 | Outputs: 27 | - A string representing the cleaned text content of the webpage. 28 | 29 | Additional aspects: 30 | - The function uses the requests library and BeautifulSoup to handle the HTTP request and HTML parsing, respectively. 31 | - The function removes script and style tags from the HTML to avoid including unwanted content in the text output. 32 | - The function uses a generator expression to split the text into lines and chunks, which can improve performance for large amounts of text. 33 | """ 34 | 35 | 36 | class TestScrapeText: 37 | # Tests that scrape_text() returns the expected text when given a valid URL. 38 | def test_scrape_text_with_valid_url(self, mocker): 39 | # Mock the requests.get() method to return a response with expected text 40 | expected_text = "This is some sample text" 41 | mock_response = mocker.Mock() 42 | mock_response.status_code = 200 43 | mock_response.text = f"

{expected_text}

" 44 | mocker.patch("requests.Session.get", return_value=mock_response) 45 | 46 | # Call the function with a valid URL and assert that it returns the expected text 47 | url = "http://www.example.com" 48 | assert scrape_text(url) == expected_text 49 | 50 | # Tests that the function returns an error message when an invalid or unreachable url is provided. 51 | def test_invalid_url(self, mocker): 52 | # Mock the requests.get() method to raise an exception 53 | mocker.patch( 54 | "requests.Session.get", side_effect=requests.exceptions.RequestException 55 | ) 56 | 57 | # Call the function with an invalid URL and assert that it returns an error message 58 | url = "http://www.invalidurl.com" 59 | error_message = scrape_text(url) 60 | assert "Error:" in error_message 61 | 62 | # Tests that the function returns an empty string when the html page contains no text to be scraped. 63 | def test_no_text(self, mocker): 64 | # Mock the requests.get() method to return a response with no text 65 | mock_response = mocker.Mock() 66 | mock_response.status_code = 200 67 | mock_response.text = "" 68 | mocker.patch("requests.Session.get", return_value=mock_response) 69 | 70 | # Call the function with a valid URL and assert that it returns an empty string 71 | url = "http://www.example.com" 72 | assert scrape_text(url) == "" 73 | 74 | # Tests that the function returns an error message when the response status code is an http error (>=400). 75 | def test_http_error(self, mocker): 76 | # Mock the requests.get() method to return a response with a 404 status code 77 | mocker.patch("requests.Session.get", return_value=mocker.Mock(status_code=404)) 78 | 79 | # Call the function with a URL 80 | result = scrape_text("https://www.example.com") 81 | 82 | # Check that the function returns an error message 83 | assert result == "Error: HTTP 404 error" 84 | 85 | # Tests that scrape_text() properly handles HTML tags. 86 | def test_scrape_text_with_html_tags(self, mocker): 87 | # Create a mock response object with HTML containing tags 88 | html = "

This is bold text.

" 89 | mock_response = mocker.Mock() 90 | mock_response.status_code = 200 91 | mock_response.text = html 92 | mocker.patch("requests.Session.get", return_value=mock_response) 93 | 94 | # Call the function with a URL 95 | result = scrape_text("https://www.example.com") 96 | 97 | # Check that the function properly handles HTML tags 98 | assert result == "This is bold text." 99 | -------------------------------------------------------------------------------- /tests/unit/test_chat.py: -------------------------------------------------------------------------------- 1 | # Generated by CodiumAI 2 | import unittest 3 | import time 4 | from unittest.mock import patch 5 | 6 | from autogpt.chat import create_chat_message, generate_context 7 | 8 | 9 | class TestChat(unittest.TestCase): 10 | # Tests that the function returns a dictionary with the correct keys and values when valid strings are provided for role and content. 11 | def test_happy_path_role_content(self): 12 | result = create_chat_message("system", "Hello, world!") 13 | self.assertEqual(result, {"role": "system", "content": "Hello, world!"}) 14 | 15 | # Tests that the function returns a dictionary with the correct keys and values when empty strings are provided for role and content. 16 | def test_empty_role_content(self): 17 | result = create_chat_message("", "") 18 | self.assertEqual(result, {"role": "", "content": ""}) 19 | 20 | # Tests the behavior of the generate_context function when all input parameters are empty. 21 | @patch("time.strftime") 22 | def test_generate_context_empty_inputs(self, mock_strftime): 23 | # Mock the time.strftime function to return a fixed value 24 | mock_strftime.return_value = "Sat Apr 15 00:00:00 2023" 25 | # Arrange 26 | prompt = "" 27 | relevant_memory = "" 28 | full_message_history = [] 29 | model = "gpt-3.5-turbo-0301" 30 | 31 | # Act 32 | result = generate_context(prompt, relevant_memory, full_message_history, model) 33 | 34 | # Assert 35 | expected_result = ( 36 | -1, 37 | 47, 38 | 3, 39 | [ 40 | {"role": "system", "content": ""}, 41 | { 42 | "role": "system", 43 | "content": f"The current time and date is {time.strftime('%c')}", 44 | }, 45 | { 46 | "role": "system", 47 | "content": f"This reminds you of these events from your past:\n\n\n", 48 | }, 49 | ], 50 | ) 51 | self.assertEqual(result, expected_result) 52 | 53 | # Tests that the function successfully generates a current_context given valid inputs. 54 | def test_generate_context_valid_inputs(self): 55 | # Given 56 | prompt = "What is your favorite color?" 57 | relevant_memory = "You once painted your room blue." 58 | full_message_history = [ 59 | create_chat_message("user", "Hi there!"), 60 | create_chat_message("assistant", "Hello! How can I assist you today?"), 61 | create_chat_message("user", "Can you tell me a joke?"), 62 | create_chat_message( 63 | "assistant", 64 | "Why did the tomato turn red? Because it saw the salad dressing!", 65 | ), 66 | create_chat_message("user", "Haha, that's funny."), 67 | ] 68 | model = "gpt-3.5-turbo-0301" 69 | 70 | # When 71 | result = generate_context(prompt, relevant_memory, full_message_history, model) 72 | 73 | # Then 74 | self.assertIsInstance(result[0], int) 75 | self.assertIsInstance(result[1], int) 76 | self.assertIsInstance(result[2], int) 77 | self.assertIsInstance(result[3], list) 78 | self.assertGreaterEqual(result[0], 0) 79 | self.assertGreaterEqual(result[1], 0) 80 | self.assertGreaterEqual(result[2], 0) 81 | self.assertGreaterEqual( 82 | len(result[3]), 3 83 | ) # current_context should have at least 3 messages 84 | self.assertLessEqual( 85 | result[1], 2048 86 | ) # token limit for GPT-3.5-turbo-0301 is 2048 tokens 87 | -------------------------------------------------------------------------------- /tests/unit/test_commands.py: -------------------------------------------------------------------------------- 1 | import autogpt.agent.agent_manager as agent_manager 2 | from autogpt.app import start_agent, list_agents, execute_command 3 | import unittest 4 | from unittest.mock import patch, MagicMock 5 | 6 | 7 | class TestCommands(unittest.TestCase): 8 | def test_make_agent(self): 9 | with patch("openai.ChatCompletion.create") as mock: 10 | obj = MagicMock() 11 | obj.response.choices[0].messages[0].content = "Test message" 12 | mock.return_value = obj 13 | start_agent("Test Agent", "chat", "Hello, how are you?", "gpt2") 14 | agents = list_agents() 15 | self.assertEqual("List of agents:\n0: chat", agents) 16 | start_agent("Test Agent 2", "write", "Hello, how are you?", "gpt2") 17 | agents = list_agents() 18 | self.assertEqual("List of agents:\n0: chat\n1: write", agents) 19 | --------------------------------------------------------------------------------