├── .github └── workflows │ ├── build.yml │ └── tests.yml ├── .gitignore ├── LICENSE ├── README.md ├── dev-requirements.txt ├── rmrkl ├── __init__.py ├── agent.py ├── executor.py ├── output_parser.py ├── prompts.py └── version.py ├── setup.py ├── test.py └── tests └── test_agent.py /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | 2 | name: publish 3 | 4 | on: 5 | release: 6 | types: 7 | - created 8 | workflow_dispatch: 9 | 10 | jobs: 11 | publish: 12 | 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v2 17 | - name: Set up Python "3.10" 18 | uses: actions/setup-python@v2 19 | with: 20 | python-version: "3.10" 21 | - name: Install dependencies 22 | run: | 23 | python -m pip install --upgrade pip 24 | if [ -f dev-requirements.txt ]; then pip install -r dev-requirements.txt; fi 25 | - name: Install 26 | run: | 27 | pip install . build 28 | - name: Run Test 29 | run: | 30 | pytest tests 31 | - name: Build a binary wheel and a source tarball 32 | run: | 33 | python -m build --sdist --wheel --outdir dist/ . 34 | - name: Publish distribution 📦 to PyPI 35 | uses: pypa/gh-action-pypi-publish@master 36 | with: 37 | password: ${{ secrets.PYPI_API_TOKEN }} 38 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | 2 | name: test 3 | 4 | on: 5 | push: 6 | branches: [ main ] 7 | pull_request: 8 | branches: [ main ] 9 | 10 | jobs: 11 | test: 12 | 13 | runs-on: ubuntu-latest 14 | strategy: 15 | matrix: 16 | python-version: [3.8, 3.9, "3.10"] 17 | 18 | steps: 19 | - uses: actions/checkout@v2 20 | - name: Set up Python ${{ matrix.python-version }} 21 | uses: actions/setup-python@v2 22 | with: 23 | python-version: ${{ matrix.python-version }} 24 | - name: Install dependencies 25 | run: | 26 | python -m pip install --upgrade pip 27 | if [ -f dev-requirements.txt ]; then pip install -r dev-requirements.txt; fi 28 | - name: Install 29 | run: | 30 | pip install . 31 | - name: Run Test 32 | run: | 33 | pytest . -------------------------------------------------------------------------------- /.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 | *.ipynb -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Andrew White 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 | # robust-mrkl 2 | 3 | A [langchain](https://github.com/hwchase17/langchain) agent that retries and utilizes a system prompt 4 | 5 | ## Install 6 | 7 | ```sh 8 | pip install rmrkl 9 | ``` 10 | 11 | ## Usage 12 | 13 | ```py 14 | from rmrkl import ChatZeroShotAgent, RetryAgentExecutor 15 | 16 | tools = ... 17 | llm = .. 18 | 19 | agent = RetryAgentExecutor.from_agent_and_tools( 20 | tools=tools, 21 | agent=ChatZeroShotAgent.from_llm_and_tools(llm, tools), 22 | verbose=True, 23 | ) 24 | agent.run(...) 25 | 26 | ``` 27 | -------------------------------------------------------------------------------- /dev-requirements.txt: -------------------------------------------------------------------------------- 1 | pytest 2 | -------------------------------------------------------------------------------- /rmrkl/__init__.py: -------------------------------------------------------------------------------- 1 | from .version import __version__ 2 | from .agent import ChatZeroShotAgent 3 | from .executor import RetryAgentExecutor 4 | -------------------------------------------------------------------------------- /rmrkl/agent.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | from langchain.chat_models.base import BaseChatModel 3 | from langchain.prompts import PromptTemplate 4 | from langchain.chains import LLMChain 5 | from langchain.callbacks.base import BaseCallbackManager 6 | from .prompts import FORMAT_INSTRUCTIONS, SUFFIX, QUESTION_PROMPT, PREFIX 7 | from langchain.agents.agent import Agent, AgentOutputParser 8 | from typing import Any, Optional, Sequence 9 | from langchain.tools import BaseTool 10 | from langchain.agents.mrkl.base import ZeroShotAgent 11 | from langchain.prompts.chat import ( 12 | ChatPromptTemplate, 13 | SystemMessagePromptTemplate, 14 | HumanMessagePromptTemplate, 15 | AIMessagePromptTemplate, 16 | ) 17 | from .output_parser import ChatZeroShotOutputParser 18 | 19 | 20 | class ChatZeroShotAgent(ZeroShotAgent): 21 | """Agent for the MRKL chain.""" 22 | 23 | @classmethod 24 | def create_prompt( 25 | cls, 26 | tools: Sequence[BaseTool], 27 | prefix: str = PREFIX, 28 | suffix: str = SUFFIX, 29 | format_instructions: str = FORMAT_INSTRUCTIONS, 30 | question_prompt: str = QUESTION_PROMPT, 31 | ) -> PromptTemplate: 32 | """Create prompt in the style of the zero shot agent. 33 | 34 | Args: 35 | tools: List of tools the agent will have access to, used to format the 36 | prompt. 37 | prefix: String to put before the list of tools. 38 | suffix: String to put after the list of tools. 39 | input_variables: List of input variables the final prompt will expect. 40 | 41 | Returns: 42 | A PromptTemplate with the template assembled from the pieces here. 43 | """ 44 | tool_strings = "\n".join( 45 | [f" {tool.name}: {tool.description}" for tool in tools] 46 | ) 47 | tool_names = ", ".join([tool.name for tool in tools]) 48 | format_instructions = format_instructions.format( 49 | tool_names=tool_names, tool_strings=tool_strings 50 | ) 51 | human_prompt = PromptTemplate( 52 | template=question_prompt, 53 | input_variables=["input"], 54 | partial_variables={"tool_strings": tool_strings}, 55 | ) 56 | human_message_prompt = HumanMessagePromptTemplate(prompt=human_prompt) 57 | ai_message_prompt = AIMessagePromptTemplate.from_template(suffix) 58 | system_message_prompt = SystemMessagePromptTemplate.from_template( 59 | '\n\n'.join( 60 | [ 61 | prefix, 62 | format_instructions 63 | ] 64 | ) 65 | ) 66 | # ignore suffix 67 | return ChatPromptTemplate.from_messages( 68 | [system_message_prompt, human_message_prompt, ai_message_prompt] 69 | ) 70 | 71 | @classmethod 72 | def from_llm_and_tools( 73 | cls, 74 | llm: BaseChatModel, 75 | tools: Sequence[BaseTool], 76 | callback_manager: Optional[BaseCallbackManager] = None, 77 | output_parser: Optional[AgentOutputParser] = ChatZeroShotOutputParser(), 78 | prefix: str = PREFIX, 79 | suffix: str = SUFFIX, 80 | format_instructions: str = FORMAT_INSTRUCTIONS, 81 | question_prompt: str = QUESTION_PROMPT, 82 | **kwargs: Any, 83 | ) -> Agent: 84 | """Construct an agent from an LLM and tools.""" 85 | cls._validate_tools(tools) 86 | prompt = cls.create_prompt( 87 | tools, 88 | prefix=prefix, 89 | suffix=suffix, 90 | format_instructions=format_instructions, 91 | question_prompt=question_prompt, 92 | ) 93 | llm_chain = LLMChain( 94 | llm=llm, 95 | prompt=prompt, 96 | callback_manager=callback_manager, 97 | ) 98 | tool_names = [tool.name for tool in tools] 99 | _output_parser = output_parser or cls._get_default_output_parser() 100 | return cls( 101 | llm_chain=llm_chain, 102 | allowed_tools=tool_names, 103 | output_parser=_output_parser, 104 | **kwargs, 105 | ) 106 | -------------------------------------------------------------------------------- /rmrkl/executor.py: -------------------------------------------------------------------------------- 1 | from typing import Dict, List, Tuple, Union, Optional 2 | 3 | from langchain.agents import AgentExecutor 4 | from langchain.schema import AgentAction, AgentFinish, OutputParserException 5 | from langchain.tools import BaseTool 6 | from langchain.callbacks.manager import CallbackManagerForChainRun 7 | 8 | 9 | class ExceptionTool(BaseTool): 10 | name = "_Exception" 11 | description = "Exception tool" 12 | 13 | def _run(self, query: str) -> str: 14 | return query 15 | 16 | async def _arun(self, query: str) -> str: 17 | return query 18 | 19 | 20 | class RetryAgentExecutor(AgentExecutor): 21 | """Agent executor that retries on output parser exceptions.""" 22 | # for backwards compatibility 23 | handle_parsing_errors: bool = True 24 | -------------------------------------------------------------------------------- /rmrkl/output_parser.py: -------------------------------------------------------------------------------- 1 | import re 2 | from typing import Any, Dict, List, Optional, Sequence, Tuple, Union 3 | 4 | import langchain 5 | from langchain import LLMChain 6 | from langchain.agents.agent import AgentOutputParser 7 | from langchain.schema import AgentAction, AgentFinish, OutputParserException 8 | 9 | from .prompts import (FINAL_ANSWER_ACTION, FORMAT_INSTRUCTIONS, 10 | QUESTION_PROMPT, SUFFIX) 11 | 12 | 13 | class ChatZeroShotOutputParser(AgentOutputParser): 14 | def get_format_instructions(self) -> str: 15 | return FORMAT_INSTRUCTIONS 16 | 17 | def parse(self, text: str) -> Union[AgentAction, AgentFinish]: 18 | if FINAL_ANSWER_ACTION in text: 19 | return AgentFinish( 20 | {"output": text.split(FINAL_ANSWER_ACTION)[-1].strip()}, text 21 | ) 22 | 23 | 24 | # Remove 'Thought' SUFFIX 25 | if text.startswith('Thought:'): 26 | text = text[8:] 27 | 28 | # \s matches against tab/newline/whitespace 29 | regex = ( 30 | r"Action\s*\d*\s*:[\s]*(.*?)[\s]*Action\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)" 31 | ) 32 | match = re.search(regex, text, re.DOTALL) 33 | if not match: 34 | raise OutputParserException(f"Could not parse LLM output: `{text}`") 35 | action = match.group(1).strip() 36 | action_input = match.group(2) 37 | return AgentAction(action, action_input.strip(" ").strip('"'), text.strip()) 38 | -------------------------------------------------------------------------------- /rmrkl/prompts.py: -------------------------------------------------------------------------------- 1 | # flake8: noqa 2 | 3 | PREFIX = """ 4 | You are an AI system. 5 | """ 6 | FORMAT_INSTRUCTIONS = """ 7 | You should only respond with a single complete 8 | Thought, Action, Action Input format 9 | OR a single Final Answer format. 10 | 11 | Complete Format: 12 | 13 | Thought: (reflect on your progress and decide what to do next) 14 | Action: (the action name, should be one of [{tool_names}]) 15 | Action Input: (the input string to the action) 16 | 17 | OR 18 | 19 | Final Answer: (the final answer to the original input question) 20 | 21 | """ 22 | QUESTION_PROMPT = """ 23 | Answer the question below using the following tools: 24 | 25 | {tool_strings} 26 | 27 | Question: {input} 28 | """ 29 | SUFFIX = """ 30 | Thought: {agent_scratchpad} 31 | """ 32 | FINAL_ANSWER_ACTION = "Final Answer:" 33 | -------------------------------------------------------------------------------- /rmrkl/version.py: -------------------------------------------------------------------------------- 1 | __version__ = "0.0.3" 2 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | exec(open("rmrkl/version.py").read()) 4 | 5 | with open("README.md", "r", encoding="utf-8") as fh: 6 | long_description = fh.read() 7 | 8 | setup( 9 | name="rmrkl", 10 | version=__version__, 11 | description="Robust Modular Reasoning, Knowledge and Language agent that uses tools and retries on failure", 12 | author="Andrew White", 13 | author_email="andrew.white@rochester.edu", 14 | url="https://github.com/whitead/robust-mrkl", 15 | license="MIT", 16 | packages=["rmrkl"], 17 | install_requires=["langchain>=0.0.157"], 18 | test_suite="tests", 19 | long_description=long_description, 20 | long_description_content_type="text/markdown", 21 | classifiers=[ 22 | "Programming Language :: Python :: 3", 23 | "License :: OSI Approved :: MIT License" 24 | ], 25 | ) 26 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | import langchain 2 | from langchain import agents 3 | from rmrkl import ChatZeroShotAgent, RetryAgentExecutor 4 | 5 | 6 | sllm = langchain.chat_models.ChatOpenAI( 7 | temperature=0.1, 8 | model_name='gpt-3.5-turbo', 9 | request_timeout=1000, 10 | max_tokens=2000 11 | ) 12 | 13 | llm = langchain.chat_models.ChatOpenAI( 14 | temperature=0.1, 15 | model_name='gpt-4', 16 | request_timeout=1000, 17 | max_tokens=2000 18 | ) 19 | 20 | 21 | tools = agents.load_tools(['python_repl'], sllm) 22 | 23 | agent = RetryAgentExecutor.from_agent_and_tools( 24 | tools=tools, 25 | agent=ChatZeroShotAgent.from_llm_and_tools( 26 | llm, 27 | tools, 28 | prefix="You are a witty AI system that follows instructions but talks in a funny way, using words like Dang!, Mate, and holy molly, whenever you can."), 29 | verbose=True, 30 | ) 31 | agent.run("What is two plus two minus one times 11. Do it step by step.") 32 | 33 | -------------------------------------------------------------------------------- /tests/test_agent.py: -------------------------------------------------------------------------------- 1 | from rmrkl import ChatZeroShotAgent, RetryAgentExecutor 2 | from langchain.llms.fake import FakeListLLM 3 | from langchain.agents import load_tools 4 | 5 | 6 | def test_agent_init(): 7 | tools = load_tools(["terminal"]) 8 | responses = [ 9 | "I should use the REPL tool", 10 | "Action: Python REPL\nAction Input: print(2 + 2)", 11 | "Final Answer: 4", 12 | ] 13 | llm = FakeListLLM(responses=responses) 14 | 15 | agent = RetryAgentExecutor.from_agent_and_tools( 16 | tools=tools, 17 | agent=ChatZeroShotAgent.from_llm_and_tools(llm, tools), 18 | verbose=True, 19 | ) 20 | agent.run("What is 2 + 2") 21 | --------------------------------------------------------------------------------