├── .gitignore ├── LICENSE ├── NOTICE ├── README.md ├── adventuregpt ├── __init__.py ├── __main__.py ├── chain.py ├── collections.py └── loop.py ├── pyproject.toml └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | 162 | # DON'T commit your OpenAI Key 163 | openai-key.txt 164 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | The file adventuregpt/__main__.py is a heavily modified version of the __main__.py file from Python Adventure by Brandon Rhodes. It is licensed under the Apache 2.0 License and below is the original license/copyright statement: 2 | 3 | Copyright 2010-2015 Brandon Rhodes. Licensed as free software under the 4 | Apache License, Version 2.0 as detailed in the accompanying README.txt. 5 | 6 | --------- 7 | 8 | The file adventuregpt/agent.py is a heavily modified version of the BabyAGI project whose license and copyright are shown below and as part of the file header: 9 | 10 | MIT License 11 | 12 | Copyright (c) 2023 Yohei Nakajima 13 | 14 | Permission is hereby granted, free of charge, to any person obtaining a copy 15 | of this software and associated documentation files (the "Software"), to deal 16 | in the Software without restriction, including without limitation the rights 17 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 18 | copies of the Software, and to permit persons to whom the Software is 19 | furnished to do so, subject to the following conditions: 20 | 21 | The above copyright notice and this permission notice shall be included in all 22 | copies or substantial portions of the Software. 23 | 24 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 25 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 26 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 27 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 28 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 29 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 30 | SOFTWARE. 31 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AdventureGPT 2 | 3 | An set of autonomous agents designed to play the 1977 game 4 | ADVENTURE or [Colossal Cave Adventure](https://en.m.wikipedia.org/wiki/Colossal_Cave_Adventure). The code base here is based off code from the following repos: 5 | 6 | * [python-adventure](https://github.com/brandon-rhodes/python-adventure) 7 | * [BabyAGI](https://github.com/yoheinakajima/babyagi) 8 | 9 | That said, code from other repos has been heavily modified and all modifications are licensed under the Apache 2.0 License. 10 | 11 | Currently, the only requirement is an OpenAI API key and to have it set as the `OPENAI_API_KEY` environment variable. 12 | 13 | ## Running 14 | 15 | Run the code by cloning the repository, navigate to the cloned repository, and run the following commands: 16 | 17 | ```bash 18 | python -m pip install -r requirements.txt 19 | python -m adventuregpt 20 | ``` 21 | Add a `--help` flag to see the command line arguments. 22 | 23 | ## TODO 24 | 25 | Here is a list of eventual goals for the project: 26 | 27 | * Add map/location agent 28 | * Win the game 29 | * Add a curses style UI for displaying tasks and prompts while showing gameplay in its own pane 30 | * Better utilization of context/memory in prompts, maybe storing results in a vector DB 31 | * Add a "replay" feature to take a history dump from a run and replay the main game text (for media creation) 32 | 33 | ## Contributing 34 | 35 | This project is a playground for me to learn more about prompt engineering and play with OpenAI's models. That said, I am interested in pushing this to the absolute limit of what is possible. If you want to contribute, make a fork and create pull requests. I will do my best to be a good steward of the project and comment on pull requests within a timely manner. 36 | -------------------------------------------------------------------------------- /adventuregpt/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oaguy1/AdventureGPT/d7153e3f73ce5e85e8f66ad2f4676fc80abc0e89/adventuregpt/__init__.py -------------------------------------------------------------------------------- /adventuregpt/__main__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create a shell through which the LLM agents can play Adventure. 3 | 4 | Copyright 2010-2015 Brandon Rhodes. 5 | Copyright 2023 Lily Hughes-Robinson. 6 | 7 | Licensed as free software under the 8 | Apache License, Version 2.0 as detailed in the accompanying README.txt. 9 | """ 10 | import argparse 11 | from adventuregpt.loop import Loop 12 | 13 | if __name__ == '__main__': 14 | parser = argparse.ArgumentParser( 15 | prog="AdventureGPT", 16 | description="The game ADVENTURE played by ChatGPT" 17 | ) 18 | parser.add_argument("-w", "--walkthrough_path") 19 | parser.add_argument("-o", "--output_path") 20 | parser.add_argument("-v", "--verbose", action="store_true") 21 | args = parser.parse_args() 22 | 23 | try: 24 | game_loop = Loop(args.walkthrough_path, args.output_path, args.verbose) 25 | game_loop.loop() 26 | except EOFError: 27 | pass 28 | except KeyboardInterrupt: 29 | pass 30 | finally: 31 | game_loop.dump_history() 32 | -------------------------------------------------------------------------------- /adventuregpt/chain.py: -------------------------------------------------------------------------------- 1 | """ 2 | LangChain LLMChains to process game i/o 3 | 4 | Copyright (c) 2023 Lily Hughes-Robinson. 5 | 6 | Licensed as free software under the 7 | Apache License, Version 2.0 as detailed in the accompanying README.txt. 8 | 9 | MIT License 10 | 11 | Copyright (c) 2023 Yohei Nakajima 12 | 13 | Permission is hereby granted, free of charge, to any person obtaining a copy 14 | of this software and associated documentation files (the "Software"), to deal 15 | in the Software without restriction, including without limitation the rights 16 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 17 | copies of the Software, and to permit persons to whom the Software is 18 | furnished to do so, subject to the following conditions: 19 | 20 | The above copyright notice and this permission notice shall be included in all 21 | copies or substantial portions of the Software. 22 | 23 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 24 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 25 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 26 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 27 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 28 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 29 | SOFTWARE. 30 | """ 31 | 32 | import os 33 | import re 34 | 35 | from langchain.chains import ConversationChain, LLMChain 36 | from langchain.chat_models import ChatOpenAI 37 | from langchain.llms import OpenAI 38 | from langchain.memory import ConversationBufferWindowMemory 39 | from langchain.prompts import PromptTemplate 40 | from langchain.prompts.chat import ( 41 | ChatPromptTemplate, 42 | ChatPromptTemplate, 43 | MessagesPlaceholder, 44 | SystemMessagePromptTemplate, 45 | HumanMessagePromptTemplate, 46 | ) 47 | from langchain.schema import BaseMessage 48 | from pydantic import root_validator 49 | from typing import Dict, List 50 | 51 | from adventuregpt.collections import SingleTaskListStorage 52 | 53 | OPENAI_TEMPERATURE = 0.0 54 | 55 | 56 | api_key = os.environ.get("OPENAI_API_KEY") 57 | 58 | if not api_key: 59 | api_key = input("OpenAI Key:") 60 | os.environ["OPENAI_API_KEY"] = api_key 61 | 62 | def openai_task_response_to_list(response: str): 63 | """ 64 | Convert a list of tasks from the format: 65 | 66 | 1. task1 67 | 2. task2 68 | 69 | into a list of tasks for later processing 70 | """ 71 | new_tasks = response.split('\n') 72 | new_tasks_list = [] 73 | for task_string in new_tasks: 74 | task_parts = task_string.strip().split(".", 1) 75 | if len(task_parts) == 2: 76 | task_id = ''.join(s for s in task_parts[0] if s.isnumeric()) 77 | task_name = re.sub(r'[^\w\s_]+', '', task_parts[1]).strip() 78 | if task_name.strip() and task_id.isnumeric(): 79 | new_tasks_list.append(task_name) 80 | 81 | return [{"task_name": task_name} for task_name in new_tasks_list] 82 | 83 | 84 | def langchain_history_to_prompt(history: List[BaseMessage]) -> str: 85 | """ 86 | Given a set of historical messages from a LangChain memory class, return a nicely 87 | formatted string for inclusion in a prompt, attempts to match what LangChain does for 88 | ConversationChains w/ memory 89 | """ 90 | prompt = "" 91 | for msg in history: 92 | # remove trailing whitespace 93 | cleaned_content = msg.content 94 | while cleaned_content[-1] == '\n': 95 | cleaned_content = cleaned_content[:-1] 96 | 97 | if msg.type == "ai": 98 | prompt += f"{msg.type.upper()}: {cleaned_content}\n" 99 | else: 100 | prompt += f"{msg.type.capitalize()}: {cleaned_content}\n" 101 | 102 | if msg.type == "human": 103 | prompt += "\n\n" 104 | 105 | return prompt 106 | 107 | class WalkthroughGameTaskCreationAgent: 108 | """ 109 | Agent that creates a list of game tasks to complete based on a given walthrough. 110 | """ 111 | 112 | def __init__(self, verbose: bool = False): 113 | self.llm = OpenAI(temperature=OPENAI_TEMPERATURE) 114 | self.prompt = PromptTemplate( 115 | input_variables=["walkthrough"], 116 | template=""" 117 | You are an agent tasked with creating a list of tasks in order win the text based adventure game Colossal Cave Adventure. 118 | 119 | Please utilize the following walkthrough to win the game: 120 | 121 | {walkthrough} 122 | 123 | Return one task per line in your response. The result must be a numbered list in the format: 124 | 125 | #. First task 126 | #. Second task 127 | 128 | The number of each entry must be followed by a period. 129 | Unless your list is empty, do not include any headers before your numbered list or follow your numbered list with any other output. 130 | """) 131 | self.chain = LLMChain(prompt=self.prompt, llm=self.llm, verbose=verbose) 132 | 133 | 134 | def run(self, walkthrough: str) -> SingleTaskListStorage: 135 | """ 136 | Creates a list of game tasks to complete based game history 137 | 138 | Args: 139 | walkthrough (str): The text of the walkthrough to summarize 140 | 141 | Returns: 142 | SingleTaskListStorage: A list of tasks to be completed to beat the game 143 | 144 | """ 145 | response = self.chain.run(walkthrough=walkthrough) 146 | task_list = openai_task_response_to_list(response) 147 | return SingleTaskListStorage(task_list) 148 | 149 | 150 | class PrioritizationAgent: 151 | """ 152 | Agent that given a SingleTaskListStorage prioritizes the task list to be more effective 153 | """ 154 | 155 | def __init__(self, verbose: bool = False): 156 | self.llm = OpenAI(temperature=OPENAI_TEMPERATURE) 157 | self.prompt = PromptTemplate( 158 | input_variables=["tasks"], 159 | template=""" 160 | You are tasked with prioritizing a task list 161 | 162 | Consider the ultimate objective of winning the game. 163 | 164 | Tasks should be sorted from highest to lowest priority, where higher-priority tasks are those that act as pre-requisites or are more essential for meeting the objective. 165 | Do not remove any tasks. Return the ranked tasks as a numbered list in the format: 166 | 167 | #. First task 168 | #. Second task 169 | 170 | The entries must be consecutively numbered, starting with 1. The number of each entry must be followed by a period. 171 | Do not include any headers before your ranked list or follow your list with any other output. 172 | 173 | These are the tasks : {tasks} 174 | """) 175 | self.chain = LLMChain(prompt=self.prompt, llm=self.llm, verbose=verbose) 176 | 177 | 178 | def run(self, task_storage: SingleTaskListStorage) -> SingleTaskListStorage: 179 | """ 180 | Creates a list of game tasks to complete based game history 181 | 182 | Args: 183 | task_storage (SingleTaskListStorage): The current task list 184 | 185 | Returns: 186 | SingleTaskListStorage: A list of tasks to be completed to beat the game 187 | 188 | """ 189 | task_names = task_storage.get_task_names() 190 | bullet_string = '\n' 191 | response = self.chain.run(tasks=bullet_string + bullet_string.join(task_names)) 192 | if not response: 193 | # Received empty response from priotritization agent. Keeping task list unchanged. 194 | return task_storage 195 | 196 | new_tasks = openai_task_response_to_list(response) 197 | return SingleTaskListStorage(new_tasks) 198 | 199 | 200 | class CustomConversationChain(ConversationChain): 201 | """ 202 | Custom ConversationChain with more variables, removes validation 203 | """ 204 | 205 | @root_validator 206 | def validate_prompt_input_variables(cls, values: Dict) -> Dict: 207 | """ 208 | don't perform the validation, just pass the values 209 | """ 210 | return values 211 | 212 | 213 | class PlayerAgent: 214 | """ 215 | Agent that executes a task based on the given objective and previous game history 216 | """ 217 | 218 | def __init__(self, verbose: bool = False): 219 | self.llm = ChatOpenAI(temperature=OPENAI_TEMPERATURE) 220 | self.memory = ConversationBufferWindowMemory(return_messages=True, input_key="input", k=15) 221 | self.prompt = ChatPromptTemplate.from_messages([ 222 | SystemMessagePromptTemplate.from_template(""" 223 | You are playing the 1977 classic Colossal Cave. 224 | 225 | If you ask the same question in a loop, use the "help" command to get out of the loop. Don't get frustrated and only take one item at a time. 226 | 227 | The games text parser is limited, keep your commands to one action and 1-3 words. Enter a single command for each prompt. Use the following guide to beat the game. Look around and e what is visible. if your objective is invisible, keep moving. You can only move north, south, east, and west. 228 | 229 | Choose the next game input based on the following objective: {objective} 230 | 231 | The following objectives have been completed: 232 | 233 | {completed_tasks} 234 | 235 | """), 236 | MessagesPlaceholder(variable_name="history"), 237 | HumanMessagePromptTemplate.from_template("{input}") 238 | ]) 239 | self.conversation = CustomConversationChain(memory=self.memory, prompt=self.prompt, llm=self.llm, verbose=verbose) 240 | 241 | 242 | def run(self, objective: str, message: str, completed_tasks: SingleTaskListStorage) -> SingleTaskListStorage: 243 | """ 244 | Creates a list of game tasks to complete based game history 245 | 246 | Args: 247 | objective (str): next game taks 248 | message (str): next game output 249 | completed_tasks (SingleTaskListStorage): list of completed tasks 250 | 251 | Returns: 252 | str: the next game input 253 | 254 | """ 255 | task_names = completed_tasks.get_task_names() 256 | bullet_string = '\n' 257 | return self.conversation.predict(input=message, objective=objective, completed_tasks=task_names) 258 | 259 | 260 | class TaskCompletionAgent: 261 | """ 262 | Agent that decides if the current objective has been completed 263 | """ 264 | 265 | def __init__(self, verbose: bool = False): 266 | self.llm = OpenAI(temperature=OPENAI_TEMPERATURE) 267 | self.prompt = PromptTemplate( 268 | input_variables=["objective", "history", "input"], 269 | template=""" 270 | You are playing the 1977 classic Colossal Cave. 271 | 272 | Decide if the current objective has been completed. 273 | 274 | Objective: {objective} 275 | 276 | Reply with a simple "COMPLETE" or "INCOMPLETE". 277 | 278 | Below is the history of the game interactions: 279 | 280 | {history} 281 | Human: {input}""") 282 | self.chain = LLMChain(prompt=self.prompt, llm=self.llm, verbose=verbose) 283 | 284 | 285 | def run(self, objective: str, history: ConversationBufferWindowMemory, message: str,) -> SingleTaskListStorage: 286 | """ 287 | Creates a list of game tasks to complete based game history 288 | 289 | Args: 290 | objective (str): current game objective 291 | message (str): next game input 292 | 293 | Returns: 294 | bool: whether the task is complete or not 295 | 296 | """ 297 | formatted_history = langchain_history_to_prompt(history.load_memory_variables({})['history']) 298 | return self.chain.run(objective=objective, history=formatted_history, input=message.strip()).lower() == "complete" 299 | 300 | 301 | class GameTaskCreationAgent: 302 | """ 303 | Agent that creates a list of game tasks to complete based game history 304 | """ 305 | 306 | def __init__(self, verbose: bool = False): 307 | self.llm = ChatOpenAI(temperature=OPENAI_TEMPERATURE) 308 | self.prompt = PromptTemplate( 309 | input_variables=["history", "input"], 310 | template=""" 311 | You are an agent tasked with creating a list of tasks in order win the text based adventure game Colossal Cave Adventure. 312 | 313 | Here is a guide on how to win: 314 | 315 | 1. Explore every space, You may have to move in a direction rather than entering directly 316 | 2. Examine or read every object. There may be more details that will help later on 317 | 3. Pick up or take every object you can. Inventory command will remind you of what you have. If you hit a limit of what you can carry, you may need to drop some items 318 | 4. Try any and every very you can think of when in new spaces. Experimenting is required to beat every textbased adventure 319 | 320 | Return one task per line in your response. The result must be a numbered list in the format: 321 | 322 | #. First task 323 | #. Second task 324 | 325 | The number of each entry must be followed by a period. 326 | 327 | Unless your list is empty, do not include any headers before your numbered list or follow your numbered list with any other output. 328 | 329 | Take into account the game history attached here: 330 | 331 | {history} 332 | Human: {input}""") 333 | self.chain = LLMChain(prompt=self.prompt, llm=self.llm, verbose=verbose) 334 | 335 | 336 | def run(self, history: ConversationBufferWindowMemory, message: str) -> SingleTaskListStorage: 337 | """ 338 | Creates a list of game tasks to complete based game history 339 | 340 | Args: 341 | message (str): next game input 342 | 343 | Returns: 344 | SingleTaskListStorage: A list of tasks to be completed to beat the game 345 | 346 | """ 347 | formatted_history = langchain_history_to_prompt(history.load_memory_variables({})['history']) 348 | response = self.chain.run(history=formatted_history, input=message) 349 | task_list = openai_task_response_to_list(response) 350 | return SingleTaskListStorage(task_list) 351 | -------------------------------------------------------------------------------- /adventuregpt/collections.py: -------------------------------------------------------------------------------- 1 | """ 2 | LangChain LLMChains to process game i/o 3 | 4 | Copyright (c) 2023 Lily Hughes-Robinson. 5 | 6 | Licensed as free software under the 7 | Apache License, Version 2.0 as detailed in the accompanying README.txt. 8 | 9 | MIT License 10 | 11 | Copyright (c) 2023 Yohei Nakajima 12 | 13 | Permission is hereby granted, free of charge, to any person obtaining a copy 14 | of this software and associated documentation files (the "Software"), to deal 15 | in the Software without restriction, including without limitation the rights 16 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 17 | copies of the Software, and to permit persons to whom the Software is 18 | furnished to do so, subject to the following conditions: 19 | 20 | The above copyright notice and this permission notice shall be included in all 21 | copies or substantial portions of the Software. 22 | 23 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 24 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 25 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 26 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 27 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 28 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 29 | SOFTWARE. 30 | """ 31 | 32 | from collections import deque 33 | from typing import Dict, List 34 | 35 | 36 | class SingleTaskListStorage: 37 | """ 38 | A task list for storing game tasks 39 | """ 40 | 41 | def __init__(self, initial_list: list = []): 42 | self.tasks = deque(initial_list or []) 43 | self.task_id_counter = 0 44 | 45 | def append(self, task: Dict): 46 | self.tasks.append(task) 47 | 48 | def replace(self, tasks: List[Dict]): 49 | self.tasks = deque(tasks) 50 | 51 | def popleft(self): 52 | return self.tasks.popleft() 53 | 54 | def is_empty(self): 55 | return False if self.tasks else True 56 | 57 | def next_task_id(self): 58 | self.task_id_counter += 1 59 | return self.task_id_counter 60 | 61 | def get_task_names(self): 62 | return [t["task_name"] for t in self.tasks] 63 | 64 | def __repr__(self): 65 | return self.tasks 66 | 67 | def __str__(self): 68 | return "\n".join([f'{i}. {t["task_name"]}' for i, t in enumerate(self.tasks)]) 69 | 70 | @classmethod 71 | def concat(cls, a, b): 72 | """ 73 | Concatenate the tasks from two lists together 74 | """ 75 | return cls(a.tasks + b.tasks) -------------------------------------------------------------------------------- /adventuregpt/loop.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create a shell through which the LLM agents can play Adventure. 3 | 4 | Copyright 2010-2015 Brandon Rhodes. 5 | Copyright 2023 Lily Hughes-Robinson. 6 | 7 | Licensed as free software under the 8 | Apache License, Version 2.0 as detailed in the accompanying README.txt. 9 | """ 10 | import functools 11 | import operator 12 | import re 13 | import sys 14 | import pprint 15 | from time import sleep 16 | 17 | from adventure import load_advent_dat 18 | from adventure.game import Game 19 | from langchain.text_splitter import CharacterTextSplitter 20 | 21 | from adventuregpt.chain import ( 22 | GameTaskCreationAgent, 23 | WalkthroughGameTaskCreationAgent, 24 | PrioritizationAgent, 25 | PlayerAgent, 26 | TaskCompletionAgent 27 | ) 28 | from adventuregpt.collections import SingleTaskListStorage 29 | 30 | 31 | BAUD = 1200 32 | 33 | 34 | class Loop(): 35 | """ 36 | The loop that does it all! Inits and plays the game in a loop until the 37 | game is won or an exception is thrown 38 | """ 39 | 40 | def __init__(self, walkthrough_path: str = "", output_file_path: str = "game_output.txt", verbose: bool = False): 41 | self.history = [] 42 | self.game_tasks = SingleTaskListStorage() 43 | self.completed_tasks = SingleTaskListStorage() 44 | self.walkthrough_path = walkthrough_path 45 | self.output_file_path = output_file_path 46 | self.current_task = None 47 | self.verbose = verbose 48 | 49 | self.game = Game() 50 | load_advent_dat(self.game) 51 | self.game.start() 52 | self.curr_game_output = self.game.output 53 | 54 | def run(self, user_input:str) -> str: 55 | """ 56 | For use as a tool for LangChain agent 57 | """ 58 | if not self.game.is_finished: 59 | # Ask Player Agent what to do next 60 | self.history.append({"role": "assistant", "content": user_input}) 61 | 62 | # split lines by newlines and periods and flatten list 63 | newline_split = user_input.lower().split('\n') 64 | period_split = [ line.split('.') for line in newline_split ] 65 | split_lines = functools.reduce(operator.iconcat, period_split, []) 66 | 67 | # We got input! Act on it. 68 | for line in split_lines: 69 | words = re.findall(r'\w+', line) 70 | if words: 71 | self.curr_game_output = self.game.do_command(words) 72 | self.history.append({ 73 | "role": "system", "content": self.curr_game_output 74 | }) 75 | self.baudout(f"> {line}\n\n") 76 | self.baudout(self.curr_game_output) 77 | else: 78 | return "COMPLETED" 79 | 80 | 81 | def next_game_task(self): 82 | """ 83 | Get the next game task 84 | """ 85 | print("***************** TASK LIST *******************") 86 | print(self.game_tasks) 87 | print() 88 | if self.current_task: 89 | self.completed_tasks.append({"task_name": self.current_task}) 90 | 91 | next_task = self.game_tasks.popleft() 92 | if next_task: 93 | self.current_task = next_task["task_name"] 94 | 95 | def baudout(self, s: str): 96 | """" 97 | Output text like an old-school terminal 98 | """ 99 | out = sys.stdout 100 | for c in s: 101 | sleep(9. / BAUD) # 8 bits + 1 stop bit @ the given baud rate 102 | out.write(c) 103 | out.flush() 104 | 105 | def dump_history(self): 106 | """ 107 | Pretty print game output to a file 108 | """ 109 | with open(self.output_file_path, 'w') as f: 110 | pprint.pprint(self.history, stream=f) 111 | 112 | def loop(self): 113 | """ 114 | Main Game Loop 115 | """ 116 | # initialize agents 117 | self.game_task_creation_agent = GameTaskCreationAgent(self.verbose) 118 | self.walkthrough_game_task_creation_agent = WalkthroughGameTaskCreationAgent(self.verbose) 119 | self.prioritization_agent = PrioritizationAgent(self.verbose) 120 | self.player_agent = PlayerAgent(self.verbose) 121 | self.task_completion_agent = TaskCompletionAgent(self.verbose) 122 | 123 | print("***************** INITIALIZING GAME *******************") 124 | # if usng walkthrough, read into memory in chunks of 500ish tokens 125 | # and pass to walkthrough gametask agent, else use gametask_creation_agent 126 | # with the limited history 127 | if self.walkthrough_path: 128 | chunk_size = 300 129 | chunk_overlap = 10 130 | 131 | with open(self.walkthrough_path, 'r') as f: 132 | walkthrough = f.read() 133 | text_splitter = CharacterTextSplitter.from_tiktoken_encoder( 134 | chunk_size=chunk_size, chunk_overlap=chunk_overlap 135 | ) 136 | text_chunks = text_splitter.split_text(walkthrough) 137 | 138 | for chunk in text_chunks: 139 | tasks = self.walkthrough_game_task_creation_agent.run(chunk) 140 | self.game_tasks.concat(tasks) 141 | else: 142 | self.game_tasks = self.game_task_creation_agent.run(self.player_agent.memory, self.curr_game_output) 143 | 144 | self.next_game_task() 145 | self.baudout(self.curr_game_output) 146 | self.history.append({ 147 | "role": "system", "content": self.curr_game_output 148 | }) 149 | 150 | while not self.game.is_finished: 151 | # Ask Player Agent what to do next 152 | result = self.player_agent.run(self.current_task, self.curr_game_output, self.completed_tasks) 153 | self.history.append({"role": "assistant", "content": result}) 154 | 155 | # split lines by newlines and periods and flatten list 156 | newline_split = result.lower().split('\n') 157 | period_split = [ line.split('.') for line in newline_split ] 158 | split_lines = functools.reduce(operator.iconcat, period_split, []) 159 | 160 | # We got input! Act on it. 161 | for line in split_lines: 162 | words = re.findall(r'\w+', line) 163 | if words: 164 | self.curr_game_output = self.game.do_command(words) 165 | self.history.append({ 166 | "role": "system", "content": self.curr_game_output 167 | }) 168 | self.baudout(f"> {line}\n\n") 169 | self.baudout(self.curr_game_output) 170 | 171 | # if not using a walthrough, come up with more tasks and prioritize 172 | if not self.walkthrough_path: 173 | new_tasks = self.game_task_creation_agent.run(self.player_agent.memory, self.curr_game_output) 174 | curr_tasks = self.game_tasks 175 | self.game_tasks = SingleTaskListStorage.concat(curr_tasks, new_tasks) 176 | self.game_tasks = self.prioritization_agent.run(self.game_tasks) 177 | 178 | completed = self.task_completion_agent.run(self.current_task, self.player_agent.memory, self.curr_game_output) 179 | if completed: 180 | self.next_game_task() -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "adventuregpt" 3 | version = "1.0.1" 4 | authors = [ 5 | { name="Lily Hughes-Robinson", email="oaguy1@gmail.com" }, 6 | ] 7 | description = "The game ADVENTURE played by ChatGPT" 8 | readme = "README.md" 9 | requires-python = ">=3.7" 10 | classifiers = [ 11 | "Programming Language :: Python :: 3", 12 | "License :: OSI Approved :: Apache Software License", 13 | "Operating System :: OS Independent", 14 | ] 15 | dependencies = [ 16 | "adventure ~=1.6", 17 | "openai ~=0.27.7", 18 | "langchain==0.0.189", 19 | ] 20 | 21 | [build-system] 22 | requires = ["setuptools>=61.0"] 23 | build-backend = "setuptools.build_meta" 24 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | adventure==1.6 2 | aiohttp==3.8.4 3 | aiosignal==1.3.1 4 | async-timeout==4.0.2 5 | attrs==23.1.0 6 | certifi==2023.5.7 7 | charset-normalizer==3.1.0 8 | dataclasses-json==0.5.7 9 | frozenlist==1.3.3 10 | greenlet==2.0.2 11 | idna==3.4 12 | langchain==0.0.209 13 | langchainplus-sdk==0.0.17 14 | marshmallow==3.19.0 15 | marshmallow-enum==1.5.1 16 | multidict==6.0.4 17 | mypy-extensions==1.0.0 18 | numexpr==2.8.4 19 | numpy==1.24.3 20 | openai==0.27.7 21 | openapi-schema-pydantic==1.2.4 22 | packaging==23.1 23 | pydantic==1.10.8 24 | PyYAML==6.0 25 | regex==2023.6.3 26 | requests==2.31.0 27 | SQLAlchemy==2.0.15 28 | tenacity==8.2.2 29 | tiktoken==0.4.0 30 | tqdm==4.65.0 31 | typing-inspect==0.9.0 32 | typing_extensions==4.6.3 33 | urllib3==2.0.2 34 | yarl==1.9.2 35 | --------------------------------------------------------------------------------