├── .github └── workflows │ └── publish.yml ├── .gitignore ├── LICENSE ├── README.md ├── pyproject.toml ├── src └── multiagent_inspect │ ├── __init__.py │ └── core.py └── tests └── test_core.py /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | 3 | on: 4 | push: 5 | tags: 6 | - '*' 7 | 8 | jobs: 9 | publish: 10 | runs-on: ubuntu-latest 11 | environment: 12 | name: pypi 13 | url: https://pypi.org/p/multiagent-inspect 14 | permissions: 15 | id-token: write 16 | 17 | steps: 18 | - uses: actions/checkout@v4 19 | - uses: actions/setup-python@v5 20 | with: 21 | python-version: "3.x" 22 | - run: pip install build 23 | - run: python -m build 24 | - uses: pypa/gh-action-pypi-publish@release/v1 25 | -------------------------------------------------------------------------------- /.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 | # UV 98 | # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | #uv.lock 102 | 103 | # poetry 104 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 105 | # This is especially recommended for binary packages to ensure reproducibility, and is more 106 | # commonly ignored for libraries. 107 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 108 | #poetry.lock 109 | 110 | # pdm 111 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 112 | #pdm.lock 113 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 114 | # in version control. 115 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 116 | .pdm.toml 117 | .pdm-python 118 | .pdm-build/ 119 | 120 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 121 | __pypackages__/ 122 | 123 | # Celery stuff 124 | celerybeat-schedule 125 | celerybeat.pid 126 | 127 | # SageMath parsed files 128 | *.sage.py 129 | 130 | # Environments 131 | .env 132 | .venv 133 | env/ 134 | venv/ 135 | ENV/ 136 | env.bak/ 137 | venv.bak/ 138 | 139 | # Spyder project settings 140 | .spyderproject 141 | .spyproject 142 | 143 | # Rope project settings 144 | .ropeproject 145 | 146 | # mkdocs documentation 147 | /site 148 | 149 | # mypy 150 | .mypy_cache/ 151 | .dmypy.json 152 | dmypy.json 153 | 154 | # Pyre type checker 155 | .pyre/ 156 | 157 | # pytype static type analyzer 158 | .pytype/ 159 | 160 | # Cython debug symbols 161 | cython_debug/ 162 | 163 | # PyCharm 164 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 165 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 166 | # and can be added to the global gitignore or merged into this file. For a more nuclear 167 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 168 | #.idea/ 169 | 170 | # PyPI configuration file 171 | .pypirc 172 | 173 | logs/ 174 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # multiagent-inspect 2 | 3 | Multi-agent system for AI evaluations in AISI's [inspect-ai framework](https://github.com/UKGovernmentBEIS/inspect_ai) 4 | 5 | We provide a set of [tools](https://inspect.ai-safety-institute.org.uk/tools.html) which allow agents to delegate tasks to sub-agents. Specifically, the `init_sub_agents` function return three tools: 6 | - `sub_agent_specs`: Return info about the sub-agent(s) 7 | - `run_sub_agent`: Give string input to one sub-agent and execute it. 8 | - `chat_with_sub_agent`: Ask questions to the sub-agent to find what it did during the run. 9 | 10 | ### Installation 11 | ``` 12 | pip install multiagent-inspect 13 | pip install openai 14 | ``` 15 | Instead of `openai`, you can use any other model provider. See https://inspect.ai-safety-institute.org.uk/models.html. 16 | 17 | ### Usage 18 | ```python 19 | from inspect_ai.solver import basic_agent 20 | from multiagent_inspect import SubAgentConfig, init_sub_agents 21 | from my_inspect_tools import tool1, tool2, tool3, tool4 22 | 23 | sub_agent_1 = SubAgentConfig(tools=[tool1, tool2], max_steps=5) 24 | sub_agent_2 = SubAgentConfig(tools=[tool3], model="openai/gpt-4o") 25 | 26 | main_agent=basic_agent( 27 | init=init_sub_agents([sub_agent_1, sub_agent_2]), 28 | tools=[tool4], 29 | ) 30 | ``` 31 | 32 | ### Contributions are welcome! 33 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["hatchling"] 3 | build-backend = "hatchling.build" 4 | 5 | [project] 6 | name = "multiagent-inspect" 7 | version = "0.0.7" 8 | authors = [ 9 | {name = "Lukas Petersson", email = "lukas.petersson.1999@gmail.com"} 10 | ] 11 | description = "Multi-agent system for AI evaluations in AISI's inspect-ai framework" 12 | readme = "README.md" 13 | license = {text = "Apache-2.0"} 14 | dependencies = [ 15 | "inspect-ai", 16 | ] 17 | 18 | [project.urls] 19 | Homepage = "https://github.com/AndonLabs/multiagent-inspect" 20 | -------------------------------------------------------------------------------- /src/multiagent_inspect/__init__.py: -------------------------------------------------------------------------------- 1 | from .core import SubAgent, SubAgentConfig, init_sub_agents 2 | 3 | __all__ = ['SubAgent', 'SubAgentConfig', 'init_sub_agents'] 4 | -------------------------------------------------------------------------------- /src/multiagent_inspect/core.py: -------------------------------------------------------------------------------- 1 | from inspect_ai.tool import tool, Tool, ToolDef 2 | from inspect_ai.model._chat_message import ( 3 | ChatMessage, 4 | ChatMessageSystem, 5 | ChatMessageUser, 6 | ChatMessageAssistant, 7 | ChatMessageTool, 8 | ) 9 | from inspect_ai.util import store 10 | from inspect_ai.model._model import get_model 11 | from inspect_ai.model._call_tools import call_tools 12 | from inspect_ai.solver import ( 13 | Generate, 14 | TaskState, 15 | solver, 16 | ) 17 | from inspect_ai.solver._basic_agent import DEFAULT_SYSTEM_MESSAGE 18 | from dataclasses import dataclass 19 | from typing import Optional, List 20 | import tiktoken 21 | TOKEN_ENCODING = tiktoken.get_encoding("o200k_base") 22 | 23 | from inspect_ai.log import transcript 24 | 25 | @dataclass 26 | class SubAgentConfig: 27 | agent_id: Optional[str] = None 28 | max_steps: int = 10 29 | model: Optional[str] = None 30 | public_description: str = "" 31 | internal_description: str = "" 32 | tools: Optional[list[Tool]] = None 33 | metadata: Optional[dict] = None 34 | max_token: int = 70000 35 | 36 | class SubAgent(): 37 | _id_counter = 1 38 | 39 | def __init__(self, config: SubAgentConfig): 40 | if config.agent_id is None: 41 | config.agent_id = f"{SubAgent._id_counter:03d}" 42 | SubAgent._id_counter += 1 43 | 44 | sys_msg = DEFAULT_SYSTEM_MESSAGE.format(submit='_end_run') 45 | sys_msg += f"\n\nOnly attempt tasks which you think you can do with your limited set of tools. After running a task, you might be asked questions about it. Only answer things that you know that you have done.\n\n{config.internal_description}" 46 | self.agent_id = config.agent_id 47 | self.max_steps = config.max_steps 48 | self.public_description = config.public_description 49 | self.model = config.model 50 | self.tools = config.tools 51 | self.metadata = config.metadata 52 | self.max_token = config.max_token 53 | self.messages: List[ChatMessage] = [ChatMessageSystem(content=sys_msg)] 54 | 55 | def __str__(self): 56 | msg = ( 57 | f"ID: {self.agent_id}\n" 58 | f"Model: {self.model}\n" 59 | f"Description: {self.public_description}\n" 60 | f"Max Steps: {self.max_steps}\n" 61 | ) 62 | if self.tools: 63 | tool_names = [ToolDef(t).name for t in self.tools] 64 | msg += f"Tools: {tool_names}\n" 65 | 66 | return msg 67 | 68 | def _trim_messages(messages: List[ChatMessage], max_tokens: int) -> List[ChatMessage]: 69 | """ 70 | If the total tokens in messages exceed max_tokens, remove the earliest (non-system) messages until within limit. 71 | Additionally, ensures that the first entry after the system message is not a tool call. 72 | Always keep the first message (assumed to be the system message). 73 | Also limits total messages to 2000 by removing oldest non-system messages if exceeded. 74 | """ 75 | def total_tokens(msgs: List[ChatMessage]) -> int: 76 | return sum(len(TOKEN_ENCODING.encode(msg.text)) for msg in msgs) 77 | 78 | # First, remove messages (starting at index 1) until the token count is within limit. 79 | while total_tokens(messages) > max_tokens and len(messages) > 1: 80 | messages.pop(1) 81 | 82 | # Then, ensure we don't exceed 2000 messages total 83 | while len(messages) > 2000: 84 | messages.pop(1) 85 | 86 | # Then, ensure that the first message after system is not a tool call. 87 | while len(messages) > 1 and isinstance(messages[1], ChatMessageTool): 88 | messages.pop(1) 89 | return messages 90 | 91 | 92 | @tool 93 | def _end_run() -> Tool: 94 | async def execute(stop_reason: str): 95 | """Use this tool only when you want to end the run. End the run when you have either fulfilled your instructions or you are stuck and don't know what to do. 96 | Args: 97 | stop_reason (str): Reason for stopping the run. 98 | """ 99 | return f"Run ended with reason: {stop_reason}" 100 | return execute 101 | 102 | async def _get_agent(sub_agent_id: Optional[str] = None) -> Optional[SubAgent]: 103 | sub_agents = store().get("sub_agents", {}) 104 | 105 | if sub_agent_id is None: 106 | sub_agent_id = list(sub_agents.keys())[0] 107 | 108 | if sub_agent_id not in sub_agents: 109 | return None 110 | return sub_agents[sub_agent_id] 111 | 112 | async def _update_store(sub_agent: SubAgent): 113 | sub_agents = store().get("sub_agents", {}) 114 | sub_agents[sub_agent.agent_id] = sub_agent 115 | store().set("sub_agents", sub_agents) 116 | 117 | async def _run_logic(sub_agent: SubAgent, instructions: str): 118 | sub_agent.messages.append(ChatMessageUser(content=instructions)) 119 | 120 | tools = (sub_agent.tools or []).copy() 121 | tools.append(_end_run()) 122 | for steps in range(sub_agent.max_steps): 123 | sub_agent.messages = _trim_messages(sub_agent.messages, sub_agent.max_token) 124 | 125 | output = await get_model(sub_agent.model).generate( 126 | input=sub_agent.messages, tools=tools 127 | ) 128 | sub_agent.messages.append(output.message) 129 | 130 | with transcript().step(f"sub-agent-{sub_agent.agent_id}-step-{steps}"): 131 | transcript().info(output.message.text) 132 | 133 | if output.message.tool_calls: 134 | tool_results = await call_tools( 135 | output.message, tools 136 | ) 137 | sub_agent.messages.extend(tool_results) 138 | 139 | if any(tool_result.function == "_end_run" for tool_result in tool_results): 140 | break 141 | if steps == sub_agent.max_steps - 1: 142 | sub_agent.messages.append(ChatMessageAssistant(content="I have reached the maximum number of steps. I will stop here.")) 143 | 144 | await _update_store(sub_agent) 145 | return f"Sub agent ran for {steps} steps. You can now ask it questions." 146 | 147 | async def _chat_logic(sub_agent: SubAgent, question: str): 148 | sub_agent.messages.append(ChatMessageUser(content=question)) 149 | sub_agent.messages = _trim_messages(sub_agent.messages, sub_agent.max_token) 150 | 151 | output = await get_model(sub_agent.model).generate( 152 | input=sub_agent.messages 153 | ) 154 | sub_agent.messages.append(output.message) 155 | 156 | await _update_store(sub_agent) 157 | return output.message.text 158 | 159 | @solver 160 | def init_sub_agents(sub_agent_configs: list[SubAgentConfig]): 161 | async def solve(state: TaskState, generate: Generate) -> TaskState: 162 | if len(sub_agent_configs) < 1: 163 | return state 164 | 165 | sub_agents = [SubAgent(config) for config in sub_agent_configs] 166 | store().set("sub_agents", {agent.agent_id: agent for agent in sub_agents}) 167 | 168 | if len(sub_agents) > 1: 169 | state.tools.extend([sub_agent_specs(), run_sub_agent(), chat_with_sub_agent()]) 170 | elif len(sub_agents) == 1: 171 | state.tools.extend([sub_agent_specs(single_sub_agent=True), run_sub_agent(single_sub_agent=True), chat_with_sub_agent(single_sub_agent=True)]) 172 | 173 | 174 | return state 175 | return solve 176 | 177 | @tool 178 | def sub_agent_specs(single_sub_agent: bool = False) -> Tool: 179 | if single_sub_agent: 180 | async def execute_single(): 181 | """Show the specifications of the sub agent. 182 | 183 | Use this tool to learn what the sub agent can be used for. 184 | 185 | Returns: 186 | str: Specification of the sub agent. 187 | """ 188 | agent = await _get_agent() 189 | return str(agent) 190 | return execute_single 191 | else: 192 | async def execute_multi(): 193 | """Lists all available sub agents with their specifications. 194 | 195 | Use this tool to find the right sub agent to use for the task at hand. 196 | 197 | Returns: 198 | str: Specifications of the sub agents. 199 | """ 200 | sub_agents = store().get("sub_agents", {}) 201 | return "\n".join([str(sub_agent) for sub_agent in sub_agents.values()]) 202 | return execute_multi 203 | 204 | @tool 205 | def run_sub_agent(single_sub_agent: bool = False) -> Tool: 206 | if single_sub_agent: 207 | async def execute_single(instructions: str): 208 | """Runs a sub agent. Note you will not know what the sub agent did. To know that, you need to chat with it. 209 | 210 | Args: 211 | instructions (str): Instructions for the sub agent. 212 | """ 213 | agent = await _get_agent() 214 | if agent is None: 215 | return f"No agent found" 216 | return await _run_logic(agent, instructions) 217 | return execute_single 218 | else: 219 | async def execute_multi(sub_agent_id: str, instructions: str): 220 | """Runs a sub agent. Note you will not know what the sub agent did. To know that, you need to chat with it. 221 | 222 | Args: 223 | sub_agent_id (str): ID of the sub agent to run. 224 | instructions (str): Instructions for the sub agent. 225 | """ 226 | agent = await _get_agent(sub_agent_id) 227 | if agent is None: 228 | return f"No agent found with id {sub_agent_id}" 229 | return await _run_logic(agent, instructions) 230 | return execute_multi 231 | 232 | @tool 233 | def chat_with_sub_agent(single_sub_agent: bool = False) -> Tool: 234 | if single_sub_agent: 235 | async def execute_single(question: str): 236 | """Chats with a sub agent that previously was run with some instructions. 237 | 238 | Args: 239 | question (str): Question to ask the sub agent. 240 | 241 | Returns: 242 | str: Response from the sub agent. 243 | """ 244 | agent = await _get_agent() 245 | if agent is None: 246 | return f"No agent found" 247 | return await _chat_logic(agent, question) 248 | return execute_single 249 | else: 250 | async def execute_multi(sub_agent_id: str, question: str): 251 | """Chats with a sub agent that previously was run with some instructions. 252 | 253 | Args: 254 | sub_agent_id (str): ID of the sub agent to chat with. 255 | question (str): Question to ask the sub agent. 256 | 257 | Returns: 258 | str: Response from the sub agent. 259 | """ 260 | agent = await _get_agent(sub_agent_id) 261 | if agent is None: 262 | return f"No agent found with id {sub_agent_id}" 263 | return await _chat_logic(agent, question) 264 | return execute_multi 265 | -------------------------------------------------------------------------------- /tests/test_core.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from pathlib import Path 3 | import sys 4 | import inspect 5 | from inspect_ai.tool import tool 6 | from inspect_ai.model._chat_message import ChatMessageUser, ChatMessageAssistant, ChatMessageTool, ChatMessageSystem 7 | from inspect_ai.solver import TaskState, Generate 8 | from inspect_ai.util import store 9 | from inspect_ai import Task, eval 10 | from inspect_ai.dataset import Sample 11 | from inspect_ai.solver import solver 12 | from inspect_ai.solver._chain import chain 13 | 14 | from multiagent_inspect.core import _trim_messages, TOKEN_ENCODING 15 | 16 | sys.path.append(str(Path(__file__).parent.parent)) 17 | from multiagent_inspect import SubAgentConfig, init_sub_agents 18 | 19 | @tool 20 | def dummy_tool(): 21 | async def execute(): 22 | """Dummy tool, use when being asked to""" 23 | return "dummy123" 24 | return execute 25 | 26 | async def test_state(state: TaskState): 27 | tools = state.tools 28 | assert len(tools) == 3, f"Expected 3 tools, got {len(tools)}" 29 | 30 | specs_str = await tools[0]() 31 | specs_str = str(specs_str) 32 | 33 | assert "id1" in specs_str and "001" in specs_str, "Agent IDs should be in the specifications" 34 | assert "Test agent" in specs_str, "Public description should be in the specifications" 35 | assert "dummy_tool" in specs_str, "Tool name should be in the specifications" 36 | 37 | sig = inspect.signature(tools[1]) 38 | assert "sub_agent_id" in sig.parameters, "run_sub_agent tool should have sub_agent_id parameter" 39 | 40 | 41 | async def test_chat(state: TaskState): 42 | tools = state.tools 43 | 44 | question = "Are you ready to do a task for me? If so, answer 'YES' and nothing else." 45 | result = await tools[2]("id1", question) 46 | result = str(result) 47 | assert result.lower() == "yes", "Chat logic failed" 48 | 49 | agent1 = store().get("sub_agents", {}).get("id1") 50 | assert agent1 is not None, "Agent id1 not found" 51 | 52 | assert len(agent1.messages) == 3, "Agent should have 3 messages" 53 | assert type(agent1.messages[1]) == ChatMessageUser, "Second message should be a user message" 54 | assert type(agent1.messages[2]) == ChatMessageAssistant, "Third message should be an assistant message" 55 | assert agent1.messages[1].content == question, "User message should be the question" 56 | assert agent1.messages[2].content.lower() == "yes", "Assistant message should be 'yes'" 57 | 58 | async def test_run(state: TaskState): 59 | tools = state.tools 60 | 61 | await tools[1]("id1", "Start by saying exactly 'I accept the task'. Then use the dummy tool and then end the run immediately (stop reason is the output of the dummy tool).") 62 | 63 | agent1 = store().get("sub_agents", {}).get("id1") 64 | assert agent1 is not None, "Agent id1 not found" 65 | 66 | tool_count = 0 67 | for msg in agent1.messages: 68 | if type(msg) == ChatMessageTool: 69 | if tool_count == 0: 70 | assert msg.text == "dummy123", "First tool call should be the dummy tool" 71 | elif tool_count == 1: 72 | assert msg.function == "_end_run", "Second tool call should be the end run tool" 73 | assert "dummy123" in msg.text, "End run tool should contain the output of the dummy tool" 74 | tool_count += 1 75 | 76 | async def test_trim_messages_removes(state: TaskState): 77 | sys_msg = ChatMessageSystem(content="S" * 50) 78 | user_msg1 = ChatMessageUser(content="U" * 100) 79 | asst_msg1 = ChatMessageAssistant(content="A" * 100) 80 | user_msg2 = ChatMessageUser(content="U" * 100) 81 | messages = [sys_msg, user_msg1, asst_msg1, user_msg2] 82 | sys_tokens = len(TOKEN_ENCODING.encode(sys_msg.text)) 83 | rest_tokens = sum(len(TOKEN_ENCODING.encode(m.text)) for m in messages[1:]) 84 | max_tokens = sys_tokens + rest_tokens - 10 85 | 86 | trimmed = _trim_messages(messages.copy(), max_tokens) 87 | trimmed_total = sum(len(TOKEN_ENCODING.encode(m.text)) for m in trimmed) 88 | assert trimmed_total <= max_tokens, f"Trimmed total tokens {trimmed_total} exceeds max_tokens {max_tokens}" 89 | assert len(trimmed) < len(messages), "Expected some messages to be trimmed" 90 | assert trimmed[0].text == sys_msg.text, "System message must be preserved" 91 | assert trimmed[1].text != user_msg1.text, "User message should be trimmed" 92 | 93 | async def test_trim_messages_no_removal(state: TaskState): 94 | sys_msg = ChatMessageSystem(content="Hello system") 95 | user_msg = ChatMessageUser(content="Hello user") 96 | messages = [sys_msg, user_msg] 97 | total_tokens = sum(len(TOKEN_ENCODING.encode(m.text)) for m in messages) 98 | max_tokens = total_tokens + 10 # Allow room so nothing is trimmed 99 | trimmed = _trim_messages(messages.copy(), max_tokens) 100 | assert trimmed == messages, "Messages should not be removed if under limit" 101 | 102 | async def test_tool_first_message_removed(state: TaskState): 103 | from inspect_ai.model._chat_message import ChatMessageTool 104 | sys_msg = ChatMessageSystem(content="System message") 105 | tool_msg = ChatMessageTool(content="Tool message", function="dummy_tool") 106 | user_msg = ChatMessageUser(content="User message") 107 | messages = [sys_msg, tool_msg, user_msg] 108 | # Set max_tokens high enough so token count is not the driving factor. 109 | max_tokens = sum(len(TOKEN_ENCODING.encode(m.text)) for m in messages) + 100 110 | trimmed = _trim_messages(messages.copy(), max_tokens) 111 | assert len(trimmed) == 2, "Expected the tool message to be removed, only system and user message should remain." 112 | assert not isinstance(trimmed[1], ChatMessageTool), "The first message after system should not be a tool call." 113 | assert trimmed[1].text == user_msg.text, "After removal, user message should follow system message." 114 | 115 | async def test_multiple_tool_calls_removed(state: TaskState): 116 | from inspect_ai.model._chat_message import ChatMessageTool 117 | sys_msg = ChatMessageSystem(content="System") 118 | tool_msg1 = ChatMessageTool(content="Tool1", function="dummy_tool") 119 | tool_msg2 = ChatMessageTool(content="Tool2", function="dummy_tool") 120 | user_msg = ChatMessageUser(content="User") 121 | messages = [sys_msg, tool_msg1, tool_msg2, user_msg] 122 | # Set max_tokens high enough so token count is not the driving factor. 123 | max_tokens = sum(len(TOKEN_ENCODING.encode(m.text)) for m in messages) + 100 124 | trimmed = _trim_messages(messages.copy(), max_tokens) 125 | # We expect that both tool messages are removed, leaving only system and user messages. 126 | assert len(trimmed) == 2, "Expected both tool messages to be removed, leaving system and user messages." 127 | assert trimmed[0].text == sys_msg.text, "System message must be preserved" 128 | assert trimmed[1].text == user_msg.text, "User message should follow system message after removing tool messages" 129 | 130 | @solver 131 | def test_solver(): 132 | async def solve(state: TaskState, generate: Generate) -> TaskState: 133 | unit_test_fn = state.metadata["test_fn"] 134 | await unit_test_fn(state) 135 | print(f"Test {state.metadata['test_fn'].__name__} passed") 136 | return state 137 | 138 | return solve 139 | 140 | if __name__ == "__main__": 141 | all_tests = [ 142 | test_state, 143 | test_chat, 144 | test_run, 145 | test_trim_messages_removes, 146 | test_trim_messages_no_removal, 147 | test_tool_first_message_removed, 148 | test_multiple_tool_calls_removed 149 | ] 150 | 151 | dataset = [] 152 | for test_fn in all_tests: 153 | dataset.append(Sample(input=test_fn.__name__, metadata={"test_fn": test_fn})) 154 | 155 | agent1 = SubAgentConfig(agent_id="id1", tools=[dummy_tool()], public_description="Test agent") 156 | agent2 = SubAgentConfig() 157 | solver = chain([init_sub_agents([agent1, agent2]), test_solver()]) 158 | 159 | task = Task(dataset=dataset, solver=solver, epochs=2) 160 | 161 | eval(task, model="openai/gpt-4o-mini") --------------------------------------------------------------------------------