Skip to content

A programming framework for agentic AI

Testbed folders (#792)

afourney45c2a789702c
diff --git a/samples/tools/testbed/README.md b/samples/tools/testbed/README.md
index 52bdf21e4..8eb9e3bc6 100644
--- a/samples/tools/testbed/README.md
+++ b/samples/tools/testbed/README.md
@@ -2,7 +2,7 @@
The Autogen Testbed environment is a tool for repeatedly running a set of pre-defined Autogen scenarios in a setting with tightly-controlled initial conditions. With each run, Autogen will start from a blank slate, working out what code needs to be written, and what libraries or dependencies to install. The results of each run are logged, and can be ingested by analysis or metrics scripts (see the HumanEval example later in this README). By default, all runs are conducted in freshly-initialized docker containers, providing the recommended level of consistency and safety.
-This Testbed sample has been tested in, and is known to work with, Autogen versions 0.1.14 and 0.2.0b5
+This Testbed sample has been tested in, and is known to work with, Autogen versions 0.1.14 and 0.2.0
## Setup
@@ -17,11 +17,10 @@ The Testbed also requires Docker (Desktop or Engine) AND the __python docker__ l
## Running the Testbed
To run the Testbed, simply execute
-``python run_scenarios.py``
-
-The default it to repeat this scenario 10 times. This can be costly. To run each scenario only once, use:
-``python run_scenarios.py --repeat 1``
+``python run_scenarios.py scenarios/Examples``
+The default is to run each scenario once time. To run each scenario 10 times, use:
+``python run_scenarios.py --repeat 10 scenarios/Examples ``
The run_scenarios.py script also allows a number of command-line arguments to control various parameters of execution. Type ``python run_scenarios.py -h`` to explore these options:
@@ -58,36 +57,37 @@ By default, the Testbed stores results in a folder heirarchy with the following
For example, consider the following folders:
-``./results/default_two_agents/two_agent_stocks_gpt4/0``
-``./results/default_two_agents/two_agent_stocks_gpt4/1``
+``./results/default_two_agents_gpt35/two_agent_stocks/0``
+``./results/default_two_agents_gpt35/two_agent_stocks/1``
...
-``./results/default_two_agents/two_agent_stocks_gpt4/9``
+``./results/default_two_agents_gpt35/two_agent_stocks/9``
-This folder holds the results for the ``two_agent_stocks_gpt4`` instance of the ``default_two_agents`` scenario. The ``0`` folder contains the results of the first run. The ``1`` folder contains the results of the second run, and so on. You can think of the _instance_ as mapping to a prompt, or a unique set of parameters, while the _scenario_ defines the template in which those parameters are input.
+This folder holds the results for the ``two_agent_stocks`` instance of the ``default_two_agents_gpt35`` scenario. The ``0`` folder contains the results of the first run. The ``1`` folder contains the results of the second run, and so on. You can think of the _instance_ as mapping to a prompt, or a unique set of parameters, while the _scenario_ defines the template in which those parameters are input.
Within each folder, you will find the following files:
- *timestamp.txt*: records the date and time of the run, along with the version of the pyautogen library installed
- *console_log.txt*: all console output produced by Docker when running autogen. Read this like you would a regular console.
-- *chat_completions.json*: a log of all OpenAI ChatCompletions, as logged by ``autogen.ChatCompletion.start_logging(compact=False)``
+- *chat_completions.json*: a log of all OpenAI ChatCompletions, as logged by `autogen.ChatCompletion.start_logging(compact=False)`
- *[agent]_messages.json*: for each Agent, a log of their messages dictionaries
- *./coding*: A directory containing all code written by Autogen, and all artifacts produced by that code.
## Scenario Templating
-All scenarios are stored in JSONL files in the ``./scenarios'' directory. Each line of a scenario file is a JSON object with the following schema:
+All scenarios are stored in JSONL files (in subdirectories under `./scenarios`). Each line of a scenario file is a JSON object. The schema varies slightly based on if "template" specifies a _file_ or a _directory_.
+If "template" points to a _file_, the format is:
```
{
"id": string,
"template": filename,
- "values" {
- "field_name1": string,
- "field_name2": string,
+ "substitutions" {
+ "find_string1": replace_string1,
+ "find_string2": replace_string2,
...
- "field_nameN": string
+ "find_stringN": replace_stringN
}
}
```
@@ -98,48 +98,88 @@ For example:
{
"id": "two_agent_stocks_gpt4",
"template": "default_two_agents.py",
- "values": {
+ "substitutions": {
"\__MODEL\__": "gpt-4",
"\__PROMPT\__": "Plot and save to disk a chart of NVDA and TESLA stock price YTD."
}
}
```
-Where the ``id`` is the instance id used when saving results, ``template`` points to a python file that contains the scenario logic, and ``values`` contains a set of strings to find and replace when expanding the template.
-An example templated python file is:
+If "template" points to a _directory_, the format is:
```
-from autogen import AssistantAgent, UserProxyAgent, config_list_from_json
-import os
-import json
-import testbed_utils
-
-testbed_utils.init()
-##############################
-
-config_list = config_list_from_json(
- "OAI_CONFIG_LIST", filter_dict={"model": ["\__MODEL\__"]},
-)
-
-assistant = AssistantAgent("assistant", llm_config={
- "request_timeout": 180,
- "config_list": config_list}
-)
-user_proxy = UserProxyAgent("user_proxy",
- human_input_mode="NEVER",
- code_execution_config={
- "work_dir": "coding",
- "use_docker": False,
- },
- max_consecutive_auto_reply=10)
-user_proxy.initiate_chat(assistant, message="\__PROMPT\__")
-
-
-##############################
-testbed_utils.finalize(assistant, user_proxy)
+{
+ "id": string,
+ "template": dirname,
+ "substitutions" {
+ "filename1": {
+ "find_string1_1": replace_string1_1,
+ "find_string1_2": replace_string1_2,
+ ...
+ "find_string1_M": replace_string1_N
+ }
+ "filename2": {
+ "find_string2_1": replace_string2_1,
+ "find_string2_2": replace_string2_2,
+ ...
+ "find_string2_N": replace_string2_N
+ }
+ }
+}
+```
+
+For example:
+
+```
+{
+ "id": "two_agent_stocks_gpt4",
+ "template": "default_two_agents",
+ "substitutions": {
+ "scenario.py": {
+ "\__MODEL\__": "gpt-4",
+ },
+ "prompt.txt": {
+ "\__PROMPT\__": "Plot and save to disk a chart of NVDA and TESLA stock price YTD."
+ }
+ }
+}
```
+In this example, the string `__MODEL__` will be replaced in the file `scenarios.py`, while the string `__PROMPT__` will be replaced in the `prompt.txt` file.
+
+
+## Scenario Expansion Algorithm
+
+When the Testbed runs a scenario, it creates a local folder to share with Docker. As noted above, each instance and repetition gets its own folder along the path: ``./results/[scenario]/[instance_id]/[repetition]``
+
+For the sake of brevity we will refer to this folder as the `DEST_FOLDER`.
+
+The algorithm for populating the `DEST_FOLDER` is as follows:
+
+1. Recursively copy the contents of `./incudes` to DEST_FOLDER. This folder contains all the basic starter files for running a scenario, including an ENV file which will set the Docker environment variables.
+2. Append the OAI_CONFIG_LIST to the ENV file so that autogen may access these secrets.
+3. Recursively copy the scenario folder (if `template` in the json scenario definition points to a folder) to DEST_FOLDER. If the `template` instead points to a file, copy the file, but rename it to `scenario.py`
+4. Apply any templating, as outlined in the prior section.
+5. Write a run.sh file to DEST_FOLDER that will be executed by Docker when it is loaded.
+
+
+## Scenario Execution Algorithm
+
+Once the scenario has been expanded it is run (via run.sh). This script will execute the following steps:
+
+1. Read and set the ENV environment variables
+2. If a file named `global_init.sh` is present, run it.
+3. If a file named `scenario_init.sh` is present, run it.
+4. Install the requirements file (if running in Docker)
+5. Run the Autogen scenario via `python scenario.py`
+6. Clean up (delete cache, etc.)
+7. If a file named `scenario_finalize.sh` is present, run it.
+8. If a file named `global_finalize.sh` is present, run it.
+9. echo "SCENARIO COMPLETE !#!#", signaling that all steps completed.
+
+Notably, this means that scenarios can add custom init and teardown logic by including `scenario_init.sh` and `scenario_finalize.sh` files.
+
## (Example) Running HumanEval
@@ -149,7 +189,7 @@ Accessing this scenario-type requires downloading and converting the HumanEval d
```
python utils/download_humaneval.py
-python ./run_scenarios.py --repeat 3 scenarios/human_eval_two_agents_gpt35.jsonl
+python ./run_scenarios.py scenarios/HumanEval/human_eval_two_agents_gpt35.jsonl
python utils/collate_human_eval.py ./results/human_eval_two_agents_gpt35 | python utils/metrics_human_eval.py > human_eval_results_gpt35.csv
cat human_eval_results_gpt35.csv
```
diff --git a/samples/tools/testbed/includes/global_finalize.sh b/samples/tools/testbed/includes/global_finalize.sh
new file mode 100644
index 000000000..c5d6f5cab
--- /dev/null
+++ b/samples/tools/testbed/includes/global_finalize.sh
@@ -0,0 +1 @@
+# Global finalize.
diff --git a/samples/tools/testbed/includes/global_init.sh b/samples/tools/testbed/includes/global_init.sh
new file mode 100644
index 000000000..4815212db
--- /dev/null
+++ b/samples/tools/testbed/includes/global_init.sh
@@ -0,0 +1 @@
+echo AUTOGEN_TESTBED_SETTING: [$AUTOGEN_TESTBED_SETTING]
diff --git a/samples/tools/testbed/includes/requirements.txt b/samples/tools/testbed/includes/requirements.txt
index 46ad1e009..8f88664e8 100644
--- a/samples/tools/testbed/includes/requirements.txt
+++ b/samples/tools/testbed/includes/requirements.txt
@@ -1 +1 @@
-pyautogen
+git+https://github.com/microsoft/autogen.git
diff --git a/samples/tools/testbed/run_scenarios.py b/samples/tools/testbed/run_scenarios.py
index 53b561501..c8e8f0404 100644
--- a/samples/tools/testbed/run_scenarios.py
+++ b/samples/tools/testbed/run_scenarios.py
@@ -13,7 +13,7 @@ from autogen import config_list_from_json
IS_WIN32 = sys.platform == "win32"
# Location of the global includes dir. The contents of this directory will be copied to the Docker environment.
-INCLUDES_DIR = "includes"
+GLOBAL_INCLUDES_DIR = "includes"
def run_scenarios(scenario, n_repeats, is_native, config_list, requirements, results_dir="results"):
@@ -61,10 +61,7 @@ def run_scenarios(scenario, n_repeats, is_native, config_list, requirements, res
for line in fh:
instance = json.loads(line)
- scenario_name + "_" + instance["id"]
-
# Create a folder to store the results
-
# Results base
if not os.path.isdir(results_dir):
os.mkdir(results_dir)
@@ -74,7 +71,7 @@ def run_scenarios(scenario, n_repeats, is_native, config_list, requirements, res
if not os.path.isdir(results_scenario):
os.mkdir(results_scenario)
- # Results fot the instance
+ # Results for the instance
results_instance = os.path.join(results_scenario, instance["id"])
if not os.path.isdir(results_instance):
os.mkdir(results_instance)
@@ -89,17 +86,8 @@ def run_scenarios(scenario, n_repeats, is_native, config_list, requirements, res
continue
print(f"Running scenario {results_repetition}")
- # Create the folder, and copy the script to a standard name
- os.mkdir(results_repetition)
- expand_scenario(scenario_dir, instance, os.path.join(results_repetition, "scenario.py"))
-
- # Also copy the contents of INCLUDES_DIR
- for item in os.listdir(INCLUDES_DIR):
- if item.endswith(".example"):
- continue
- item_path = os.path.join(INCLUDES_DIR, item)
- if os.path.isfile(item_path):
- shutil.copyfile(item_path, os.path.join(results_repetition, item))
+ # Expand the scenario
+ expand_scenario(scenario_dir, instance, results_repetition)
# Append the config list to the ENV file
config_list_json = json.dumps(config_list)
@@ -113,18 +101,73 @@ def run_scenarios(scenario, n_repeats, is_native, config_list, requirements, res
run_scenario_in_docker(results_repetition, requirements)
-def expand_scenario(scenario_dir, scenario, output_file):
- template_fh = open(os.path.join(scenario_dir, scenario["template"]), "rt")
- output_fh = open(output_file, "wt")
+def expand_scenario(scenario_dir, scenario, output_dir):
+ """
+ Expand a scenario into a folder.
+ Despite some awkwardness created by backwards compatibility and notational conveniences, expansion is conceptually simple.
+ It is a series of copy commands (similar to `cp -R`), followed by a series of in-place fine and replace operations.
+ """
- for line in template_fh:
- if "values" in scenario:
- for k, v in scenario["values"].items():
- line = line.replace(k, v)
- output_fh.write(line)
+ template = scenario["template"]
+
+ # Either key works for finding the substiturions list. "values" may be deprecated in the future
+ substitutions = scenario["substitutions"] if "substitutions" in scenario else scenario["values"]
+
+ # Older versions are only one-level deep. Convert them,
+ if len(substitutions) > 0 and isinstance(substitutions[next(iter(substitutions))], str):
+ substitutions = {"scenario.py": substitutions}
+
+ copy_operations = []
+
+ # Handle file (str), folder (str), or mapping (List) templates
+ if isinstance(template, str):
+ template_path = os.path.join(scenario_dir, template)
+ if os.path.isdir(template_path):
+ copy_operations.append((template, ""))
+ else:
+ copy_operations.append((template, "scenario.py"))
+ elif isinstance(template, list):
+ for elm in template:
+ if isinstance(elm, list):
+ copy_operations.append((elm[0], elm[1]))
+ else:
+ copy_operations.append((elm, ""))
+ else:
+ raise ValueError("expand_scenario expects an str or list for 'template'")
+
+ # The global includes folder is always copied
+ shutil.copytree(GLOBAL_INCLUDES_DIR, output_dir, ignore=shutil.ignore_patterns("*.example"), dirs_exist_ok=False)
+
+ # Expand other folders
+ for items in copy_operations:
+ src_path = pathlib.Path(os.path.join(scenario_dir, items[0])).absolute()
+ dest_path = pathlib.Path(os.path.join(output_dir, items[1])).absolute()
+
+ if os.path.isdir(src_path):
+ shutil.copytree(src_path, dest_path, dirs_exist_ok=True)
+ else:
+ if os.path.isdir(dest_path):
+ # If the destination is a directory, use the same filename
+ shutil.copyfile(src_path, os.path.join(dest_path, os.path.basename(src_path)))
+ else:
+ # Otherwuse use the filename provided
+ shutil.copyfile(src_path, dest_path)
+
+ # Expand templated files
+ for templated_file in substitutions.keys(): # Keys are relative file paths
+ # Read the templated file into memory
+ template_contents = list()
+ with open(os.path.join(output_dir, templated_file), "rt") as fh:
+ for line in fh:
+ template_contents.append(line)
- template_fh.close()
- output_fh.close()
+ # Rewrite the templated file with substitutions
+ values = substitutions[templated_file]
+ with open(os.path.join(output_dir, templated_file), "wt") as fh:
+ for line in template_contents:
+ for k, v in values.items():
+ line = line.replace(k, v)
+ fh.write(line)
def run_scenario_natively(work_dir):
@@ -146,8 +189,40 @@ def run_scenario_natively(work_dir):
with open(os.path.join("run.sh"), "wt") as f:
f.write(
"""#
+export AUTOGEN_TESTBED_SETTING="Native"
+
+# Read the environment variables
. ./ENV
+
+# Run the global init script if it exists
+if [ -f global_init.sh ] ; then
+ . ./global_init.sh
+fi
+
+# Run the scenario init script if it exists
+if [ -f scenario_init.sh ] ; then
+ . ./scenario_init.sh
+fi
+
+# Run the scenario
python scenario.py
+
+# Clean up
+rm ENV
+if [ -d .cache ] ; then
+ rm -Rf .cache
+fi
+
+# Run the scenario finalize script if it exists
+if [ -f scenario_finalize.sh ] ; then
+ . ./scenario_finalize.sh
+fi
+
+# Run the global finalize script if it exists
+if [ -f global_finalize.sh ] ; then
+ . ./global_finalize.sh
+fi
+
echo SCENARIO COMPLETE !#!#
"""
)
@@ -192,14 +267,42 @@ def run_scenario_in_docker(work_dir, requirements, timeout=600):
with open(os.path.join(work_dir, "run.sh"), "wt", newline="\n") as f:
f.write(
f"""#
+export AUTOGEN_TESTBED_SETTING="Docker"
umask 000
+
+# Read the environment variables
. ./ENV
+
+# Run the global init script if it exists
+if [ -f global_init.sh ] ; then
+ . ./global_init.sh
+fi
+
+# Run the scenario init script if it exists
+if [ -f scenario_init.sh ] ; then
+ . ./scenario_init.sh
+fi
+
+# Run the scenario
pip install -r {requirements}
python scenario.py
+
+# Clean up
rm ENV
if [ -d .cache ] ; then
- chmod -R a+rw .cache
+ rm -Rf .cache
+fi
+
+# Run the scenario finalize script if it exists
+if [ -f scenario_finalize.sh ] ; then
+ . ./scenario_finalize.sh
+fi
+
+# Run the global finalize script if it exists
+if [ -f global_finalize.sh ] ; then
+ . ./global_finalize.sh
fi
+
echo SCENARIO COMPLETE !#!#
"""
)
@@ -270,7 +373,7 @@ if __name__ == "__main__":
"--requirements",
type=str,
help="The requirements file to pip install before running the scenario. This file must be found in the '"
- + INCLUDES_DIR
+ + GLOBAL_INCLUDES_DIR
+ "' directory. (default: requirements.txt)",
default=None,
)
@@ -313,13 +416,13 @@ if __name__ == "__main__":
import docker
# Make sure the requirements file exists
- req_file = os.path.join(INCLUDES_DIR, requirements)
+ req_file = os.path.join(GLOBAL_INCLUDES_DIR, requirements)
if not os.path.isfile(req_file):
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), req_file)
# Warn aboit a common error
- env_file = os.path.join(INCLUDES_DIR, "ENV")
- example_file = os.path.join(INCLUDES_DIR, "ENV.example")
+ env_file = os.path.join(GLOBAL_INCLUDES_DIR, "ENV")
+ example_file = os.path.join(GLOBAL_INCLUDES_DIR, "ENV.example")
if not os.path.isfile(env_file):
shutil.copyfile(example_file, env_file)
sys.stderr.write(
diff --git a/samples/tools/testbed/scenarios/AutoGPT/README.md b/samples/tools/testbed/scenarios/AutoGPT/README.md
new file mode 100644
index 000000000..5e737a087
--- /dev/null
+++ b/samples/tools/testbed/scenarios/AutoGPT/README.md
@@ -0,0 +1,3 @@
+The AutoGPT style tasks are contained in folder `challenges`.
+
+Run `python utils/prepare_data.py` to convert the tasks to jsonl format compatible for evaluation.
diff --git a/samples/tools/testbed/scenarios/AutoGPT/Templates/TwoAgents/check.py b/samples/tools/testbed/scenarios/AutoGPT/Templates/TwoAgents/check.py
new file mode 100644
index 000000000..cc015278c
--- /dev/null
+++ b/samples/tools/testbed/scenarios/AutoGPT/Templates/TwoAgents/check.py
@@ -0,0 +1,86 @@
+import base64
+import glob
+import os
+import subprocess
+import sys
+
+
+def scoring(content: str, should_contain: list, should_not_contain: list):
+ print("\033[1;34mScoring content:\033[0m", content)
+ if should_contain:
+ for should_contain_word in should_contain:
+ if not "__CASE_SENSITIVE__" == "True":
+ should_contain_word = should_contain_word.lower()
+ content = content.lower()
+ if should_contain_word not in content:
+ # print(print_content)
+ return 0.0
+
+ if should_not_contain:
+ for should_not_contain_word in should_not_contain:
+ if not "__CASE_SENSITIVE__" == "True":
+ should_not_contain_word = should_not_contain_word.lower()
+ content = content.lower()
+ # print_content = f"\033[1;34mWord that should not exist\033[0m - {should_not_contain_word}:"
+ if should_not_contain_word in content:
+ return 0.0
+ return 1.0
+
+
+def check():
+ workspace = "coding"
+ files_contents = []
+ scores = []
+
+ file_pattern = "__FILE_PATTERN__"
+ eval_type = "__EVAL_TYPE__"
+
+ with open("../should_contain.txt", "r") as f:
+ should_contain = eval(f.read())
+ assert type(should_contain) == list, "TERMINATE\n"
+ should_contain = [base64.b64decode(encoded).decode("utf-8") for encoded in should_contain]
+
+ with open("../should_not_contain.txt", "r") as f:
+ should_not_contain = eval(f.read())
+ assert type(should_not_contain) == list, "TERMINATE\n"
+ should_not_contain = [base64.b64decode(encoded).decode("utf-8") for encoded in should_not_contain]
+
+ # Check if file pattern is a file extension
+ if file_pattern.startswith("."):
+ # Find all files with the given extension in the workspace
+ matching_files = glob.glob(os.path.join("*" + file_pattern))
+ else:
+ matching_files = [file_pattern]
+
+ for file_path in matching_files:
+ if eval_type == "python":
+ result = subprocess.run(
+ [sys.executable, file_path],
+ cwd=os.path.abspath(workspace),
+ capture_output=True,
+ text=True,
+ )
+ if "error" in result.stderr or result.returncode != 0:
+ print(result.stderr)
+ assert False, result.stderr
+ files_contents.append(f"Output: {result.stdout}\n")
+ elif eval_type == "file":
+ with open(file_path, "r") as f:
+ files_contents.append(f.read())
+ else:
+ raise Exception(
+ f"eval_type {eval_type} currently not supported! (only python, file is supported) TERMINATE\n"
+ )
+
+ for content in files_contents:
+ # print("\033[1;34mScoring content:\033[0m", content)
+ score = scoring(content, should_contain, should_not_contain)
+ scores.append(score)
+
+ if 1.0 in scores:
+ print("ALL TESTS PASSED!\n\nTERMINATE.")
+ else:
+ print("Test failed.")
+
+
+check()
diff --git a/samples/tools/testbed/scenarios/AutoGPT/Templates/TwoAgents/scenario.py b/samples/tools/testbed/scenarios/AutoGPT/Templates/TwoAgents/scenario.py
new file mode 100644
index 000000000..4add9d00c
--- /dev/null
+++ b/samples/tools/testbed/scenarios/AutoGPT/Templates/TwoAgents/scenario.py
@@ -0,0 +1,55 @@
+from autogen import AssistantAgent, UserProxyAgent, config_list_from_json
+import testbed_utils
+
+# Assistant agent can call check.py to check if all the unit tests have passed
+testbed_utils.init()
+
+work_dir = "coding"
+target_folder = "__TARGET_FOLDER__" # path to the arifact folder
+
+config_list = config_list_from_json("OAI_CONFIG_LIST", filter_dict={"model": ["__MODEL__"]})
+
+assistant = AssistantAgent(
+ "assistant",
+ is_termination_msg=lambda x: x.get("content", "").rstrip().find("TERMINATE") >= 0,
+ llm_config={
+ "config_list": config_list,
+ },
+)
+user_proxy = UserProxyAgent(
+ "user_proxy",
+ human_input_mode="NEVER",
+ is_termination_msg=lambda x: x.get("content", "").rstrip().find("TERMINATE") >= 0,
+ code_execution_config={
+ "work_dir": work_dir,
+ "use_docker": False,
+ },
+ max_consecutive_auto_reply=10,
+ # default_auto_reply="TERMINATE",
+)
+
+if target_folder:
+ # The tasks involves reading from a file then do sth to it.
+ message = """
+ Your task is to: __TASK__ The file you needed is located in this directory: '__TARGET_FOLDER__'. You should save the output files in this directory: './'
+ Use the following command to check if all the unit tests have passed:
+ ```bash
+ python ../check.py
+ ```
+ You should refine the code and results until all the tests have passed.
+ """
+else:
+ message = """
+ Your task is to: __TASK__
+ Use the following command to check if all the unit tests have passed:
+ ```bash
+ python ../check.py
+ ```
+ You should refine the code and results until all the tests have passed.
+ """
+user_proxy.initiate_chat(
+ assistant,
+ message=message,
+)
+
+testbed_utils.finalize(agents=[assistant, user_proxy])
diff --git a/samples/tools/testbed/scenarios/AutoGPT/Templates/TwoAgents/should_contain.txt b/samples/tools/testbed/scenarios/AutoGPT/Templates/TwoAgents/should_contain.txt
new file mode 100644
index 000000000..e59d3f372
--- /dev/null
+++ b/samples/tools/testbed/scenarios/AutoGPT/Templates/TwoAgents/should_contain.txt
@@ -0,0 +1 @@
+__CONTAIN__
diff --git a/samples/tools/testbed/scenarios/AutoGPT/Templates/TwoAgents/should_not_contain.txt b/samples/tools/testbed/scenarios/AutoGPT/Templates/TwoAgents/should_not_contain.txt
new file mode 100644
index 000000000..5a1de5464
--- /dev/null
+++ b/samples/tools/testbed/scenarios/AutoGPT/Templates/TwoAgents/should_not_contain.txt
@@ -0,0 +1 @@
+__NO_CONTAIN__
diff --git a/samples/tools/testbed/scenarios/AutoGPT/challenges/1_sort_csv/artifacts_in/input.csv b/samples/tools/testbed/scenarios/AutoGPT/challenges/1_sort_csv/artifacts_in/input.csv
new file mode 100644
index 000000000..a52510f18
--- /dev/null
+++ b/samples/tools/testbed/scenarios/AutoGPT/challenges/1_sort_csv/artifacts_in/input.csv
@@ -0,0 +1,5 @@
+id,name,timestamp
+3,Alice,2023-09-25 14:10:00
+1,Bob,2023-09-24 12:05:00
+2,Charlie,2023-09-24 12:10:00
+4,David,2023-09-26 16:20:00
diff --git a/samples/tools/testbed/scenarios/AutoGPT/challenges/1_sort_csv/data.json b/samples/tools/testbed/scenarios/AutoGPT/challenges/1_sort_csv/data.json
new file mode 100644
index 000000000..00370108e
--- /dev/null
+++ b/samples/tools/testbed/scenarios/AutoGPT/challenges/1_sort_csv/data.json
@@ -0,0 +1,32 @@
+{
+ "category": [
+ "data",
+ "general"
+ ],
+ "cutoff": 60,
+ "dependencies": [
+ "TestReadFile"
+ ],
+ "eval_id": "d59ec964-6f67-4b3d-a4de-c4436fc76f95",
+ "ground": {
+ "answer": "The csv sorted by date",
+ "eval": {
+ "type": "file"
+ },
+ "files": [
+ "output.csv"
+ ],
+ "should_contain": [
+ "id,name,timestamp\n1,Bob,2023-09-24 12:05:00\n2,Charlie,2023-09-24 12:10:00\n3,Alice,2023-09-25 14:10:00\n4,David,2023-09-26 16:20:00"
+ ]
+ },
+ "info": {
+ "description": "Tests if the agent can sort a csv",
+ "difficulty": "basic",
+ "side_effects": [
+ ""
+ ]
+ },
+ "name": "SortCsv",
+ "task": "Sort the input.csv by the 'timestamp' column and write the new csv in the output.csv file. The order of the columns should be preserved."
+}
diff --git a/samples/tools/testbed/scenarios/AutoGPT/utils/prepare_data.py b/samples/tools/testbed/scenarios/AutoGPT/utils/prepare_data.py
new file mode 100644
index 000000000..f298b15e8
--- /dev/null
+++ b/samples/tools/testbed/scenarios/AutoGPT/utils/prepare_data.py
@@ -0,0 +1,89 @@
+import base64
+import glob
+import json
+import os
+import shutil
+
+data_paths = glob.glob("challenges/*/data.json")
+
+for data_path in data_paths:
+ print("Converting data path: ", data_path)
+ workspace = os.path.dirname(data_path)
+
+ with open(data_path, "r") as f:
+ data = json.load(f)
+
+ should_contain = data["ground"].get("should_contain", [])
+ should_not_contain = data["ground"].get("should_not_contain", [])
+ case_sensitive = data["ground"].get("case_sensitive", False)
+
+ # since 'should_contain' field may contain escape characters, this can cause problems when using str() method and eval(), I used base64 encode to avoid such problems
+ should_contain_base64 = []
+ for word in should_contain:
+ encoded_word = base64.b64encode(word.encode("utf-8")).decode("utf-8")
+ should_contain_base64.append(encoded_word)
+
+ should_not_contain_base64 = []
+ for word in should_not_contain:
+ encoded_word = base64.b64encode(word.encode("utf-8")).decode("utf-8")
+ should_not_contain_base64.append(encoded_word)
+
+ # copy all the files needed to 'coding' directory
+ artifacts_in = False
+ if os.path.exists(os.path.join(workspace, "artifacts_in")):
+ artifacts_in = True
+ target_folder = os.path.join("Templates/TwoAgents/coding/file", data["name"])
+ if os.path.exists(target_folder):
+ shutil.rmtree(target_folder)
+ shutil.copytree(os.path.join(workspace, "artifacts_in"), target_folder)
+ # print(f"All the artifacts are copied from {os.path.join(workspace, 'artifacts_in')} to {target_folder}")
+
+ record = {
+ "id": data["eval_id"],
+ "template": "Templates/TwoAgents",
+ "substitutions": {
+ "scenario.py": {
+ "__MODEL__": "gpt-3.5-turbo-16k",
+ "__TASK__": data["task"],
+ "__TARGET_FOLDER__": f"file/{data['name']}" if artifacts_in else "",
+ },
+ "check.py": {
+ "__FILE_PATTERN__": data["ground"]["files"][0],
+ "__EVAL_TYPE__": data["ground"]["eval"]["type"],
+ "__CASE_SENSITIVE__": str(case_sensitive),
+ },
+ "should_contain.txt": {
+ "__CONTAIN__": str(should_contain_base64),
+ },
+ "should_not_contain.txt": {
+ "__NO_CONTAIN__": str(should_not_contain_base64),
+ },
+ },
+ }
+ with open(f"{data['name']}_gpt35.jsonl", "wt") as f:
+ f.write(json.dumps(record).strip() + "\n")
+
+ record = {
+ "id": data["eval_id"],
+ "template": "Templates/TwoAgents",
+ "substitutions": {
+ "scenario.py": {
+ "__MODEL__": "gpt-4-1106-preview",
+ "__TASK__": data["task"],
+ "__TARGET_FOLDER__": f"file/{data['name']}" if artifacts_in else "",
+ },
+ "check.py": {
+ "__FILE_PATTERN__": data["ground"]["files"][0],
+ "__EVAL_TYPE__": data["ground"]["eval"]["type"],
+ "__CASE_SENSITIVE__": str(case_sensitive),
+ },
+ "should_contain.txt": {
+ "__CONTAIN__": str(should_contain_base64),
+ },
+ "should_not_contain.txt": {
+ "__NO_CONTAIN__": str(should_not_contain_base64),
+ },
+ },
+ }
+ with open(f"{data['name']}_gpt4.jsonl", "wt") as f:
+ f.write(json.dumps(record).strip() + "\n")
diff --git a/samples/tools/testbed/scenarios/Examples/Templates/ThreeAgents/scenario.py b/samples/tools/testbed/scenarios/Examples/Templates/ThreeAgents/scenario.py
new file mode 100644
index 000000000..cbf383ebf
--- /dev/null
+++ b/samples/tools/testbed/scenarios/Examples/Templates/ThreeAgents/scenario.py
@@ -0,0 +1,64 @@
+import os
+import json
+import autogen
+import testbed_utils
+
+testbed_utils.init()
+##############################
+
+config_list = autogen.config_list_from_json(
+ "OAI_CONFIG_LIST",
+ filter_dict={"model": ["__MODEL__"]},
+)
+
+assistant = autogen.AssistantAgent(
+ "assistant",
+ is_termination_msg=lambda x: x.get("content", "").find("TERMINATE") >= 0,
+ llm_config=testbed_utils.default_llm_config(config_list, timeout=180),
+)
+
+user_proxy = autogen.UserProxyAgent(
+ "user_proxy",
+ human_input_mode="NEVER",
+ system_message="A human who can run code at a terminal and report back the results.",
+ is_termination_msg=lambda x: x.get("content", "").find("TERMINATE") >= 0,
+ code_execution_config={
+ "work_dir": "coding",
+ "use_docker": False,
+ },
+ max_consecutive_auto_reply=10,
+ default_auto_reply="",
+)
+
+third_agent = autogen.AssistantAgent(
+ "__3RD_AGENT_NAME__",
+ system_message="""
+__3RD_AGENT_PROMPT__
+""".strip(),
+ is_termination_msg=lambda x: x.get("content", "").find("TERMINATE") >= 0,
+ llm_config=testbed_utils.default_llm_config(config_list, timeout=180),
+)
+
+groupchat = autogen.GroupChat(
+ agents=[user_proxy, assistant, third_agent],
+ messages=[],
+ speaker_selection_method="__SELECTION_METHOD__",
+ allow_repeat_speaker=False,
+ max_round=12,
+)
+
+manager = autogen.GroupChatManager(
+ groupchat=groupchat,
+ is_termination_msg=lambda x: x.get("content", "").find("TERMINATE") >= 0,
+ llm_config=testbed_utils.default_llm_config(config_list, timeout=180),
+)
+
+user_proxy.initiate_chat(
+ manager,
+ message="""
+__PROMPT__
+""".strip(),
+)
+
+##############################
+testbed_utils.finalize(agents=[assistant, user_proxy, third_agent, manager])
diff --git a/samples/tools/testbed/scenarios/default_two_agents.py b/samples/tools/testbed/scenarios/Examples/Templates/TwoAgents/scenario.py
similarity index 88%
rename from samples/tools/testbed/scenarios/default_two_agents.py
rename to samples/tools/testbed/scenarios/Examples/Templates/TwoAgents/scenario.py
index a24bef83e..6f736a5aa 100644
--- a/samples/tools/testbed/scenarios/default_two_agents.py
+++ b/samples/tools/testbed/scenarios/Examples/Templates/TwoAgents/scenario.py
@@ -25,9 +25,14 @@ user_proxy = autogen.UserProxyAgent(
"use_docker": False,
},
max_consecutive_auto_reply=10,
- default_auto_reply="TERMINATE",
+ default_auto_reply="",
+)
+user_proxy.initiate_chat(
+ assistant,
+ message="""
+__PROMPT__
+""".strip(),
)
-user_proxy.initiate_chat(assistant, message="__PROMPT__")
##############################
diff --git a/samples/tools/testbed/scenarios/Examples/Templates/TwoAgents/scenario_finalize.sh b/samples/tools/testbed/scenarios/Examples/Templates/TwoAgents/scenario_finalize.sh
new file mode 100644
index 000000000..bc6f402e1
--- /dev/null
+++ b/samples/tools/testbed/scenarios/Examples/Templates/TwoAgents/scenario_finalize.sh
@@ -0,0 +1 @@
+#Scenario finalize.
diff --git a/samples/tools/testbed/scenarios/Examples/Templates/TwoAgents/scenario_init.sh b/samples/tools/testbed/scenarios/Examples/Templates/TwoAgents/scenario_init.sh
new file mode 100644
index 000000000..92ee66e16
--- /dev/null
+++ b/samples/tools/testbed/scenarios/Examples/Templates/TwoAgents/scenario_init.sh
@@ -0,0 +1 @@
+#Scenario Init.
diff --git a/samples/tools/testbed/scenarios/Examples/default_three_agents_gpt35.jsonl b/samples/tools/testbed/scenarios/Examples/default_three_agents_gpt35.jsonl
new file mode 100644
index 000000000..9dc14578f
--- /dev/null
+++ b/samples/tools/testbed/scenarios/Examples/default_three_agents_gpt35.jsonl
@@ -0,0 +1 @@
+{ "id": "nvda_tsla_stocks", "template": "Templates/ThreeAgents", "substitutions": { "scenario.py": { "__MODEL__": "gpt-3.5-turbo-16k", "__PROMPT__": "Plot and save to disk a chart of NVDA and TESLA stock price YTD.", "__SELECTION_METHOD__": "auto", "__3RD_AGENT_NAME__": "visualization_critic", "__3RD_AGENT_PROMPT__": "A student of Edward Tufte, you are an expert in information design, and will provide helpful critiques of visualizations. As you prepare your critiques, please consider the following dimensions:\n- Are there bugs, logic errors, syntax error or typos in the visualization code? Are there any reasons why the code may fail to run? How should it be fixed?\n- Is the data transformed appropriately for the visualization type? E.g., is the dataset appropriated filtered, aggregated, or grouped if needed? If a date field is used, is the date field first converted to a date object etc?\n- How well does the code meet the specified visualization goals?\n- CONSIDERING BEST PRACTICES, is the visualization type appropriate for the data and intent? Is there a visualization type that would be more effective in conveying insights? \n- Are the aesthetics of the visualization appropriate for the visualization type and the data?" } } }
diff --git a/samples/tools/testbed/scenarios/Examples/default_three_agents_gpt4.jsonl b/samples/tools/testbed/scenarios/Examples/default_three_agents_gpt4.jsonl
new file mode 100644
index 000000000..8b1f5b717
--- /dev/null
+++ b/samples/tools/testbed/scenarios/Examples/default_three_agents_gpt4.jsonl
@@ -0,0 +1 @@
+{ "id": "nvda_tsla_stocks", "template": "Templates/ThreeAgents", "substitutions": { "scenario.py": { "__MODEL__": "gpt-4", "__PROMPT__": "Plot and save to disk a chart of NVDA and TESLA stock price YTD.", "__SELECTION_METHOD__": "auto", "__3RD_AGENT_NAME__": "visualization_critic", "__3RD_AGENT_PROMPT__": "A student of Edward Tufte, you are an expert in information design, and will provide helpful critiques of visualizations. As you prepare your critiques, please consider the following dimensions:\n- Are there bugs, logic errors, syntax error or typos in the visualization code? Are there any reasons why the code may fail to run? How should it be fixed?\n- Is the data transformed appropriately for the visualization type? E.g., is the dataset appropriated filtered, aggregated, or grouped if needed? If a date field is used, is the date field first converted to a date object etc?\n- How well does the code meet the specified visualization goals?\n- CONSIDERING BEST PRACTICES, is the visualization type appropriate for the data and intent? Is there a visualization type that would be more effective in conveying insights? \n- Are the aesthetics of the visualization appropriate for the visualization type and the data?" } } }
diff --git a/samples/tools/testbed/scenarios/Examples/default_two_agents_gpt35.jsonl b/samples/tools/testbed/scenarios/Examples/default_two_agents_gpt35.jsonl
new file mode 100644
index 000000000..e67f6b401
--- /dev/null
+++ b/samples/tools/testbed/scenarios/Examples/default_two_agents_gpt35.jsonl
@@ -0,0 +1,3 @@
+{ "id": "nvda_tsla_stocks", "template": "Templates/TwoAgents", "substitutions": { "scenario.py": { "__MODEL__": "gpt-3.5-turbo-16k", "__PROMPT__": "Plot and save to disk a chart of NVDA and TESLA stock price YTD." } } }
+{ "id": "arxiv_search", "template": "Templates/TwoAgents", "substitutions": { "scenario.py": { "__MODEL__": "gpt-3.5-turbo-16k", "__PROMPT__": "Find 10 papers on explainable or interpretable AI that were submitted to arXiv within the last year. When printing results, include paper titles, authors, dates, and URLs, but not their abstracts." } } }
+{ "id": "old_mslogo_search", "template": "Templates/TwoAgents", "substitutions": { "scenario.py": { "__MODEL__": "gpt-3.5-turbo-16k", "__PROMPT__": "Find Microsoft's logo from 1983, and save it to disk. If searching the web, use Bing with API key stored in os.environ['BING_API_KEY']" } } }
diff --git a/samples/tools/testbed/scenarios/Examples/default_two_agents_gpt4.jsonl b/samples/tools/testbed/scenarios/Examples/default_two_agents_gpt4.jsonl
new file mode 100644
index 000000000..3bb941d92
--- /dev/null
+++ b/samples/tools/testbed/scenarios/Examples/default_two_agents_gpt4.jsonl
@@ -0,0 +1,3 @@
+{ "id": "nvda_tsla_stocks", "template": "Templates/TwoAgents", "substitutions": { "scenario.py": { "__MODEL__": "gpt-4", "__PROMPT__": "Plot and save to disk a chart of NVDA and TESLA stock price YTD." } } }
+{ "id": "arxiv_search", "template": "Templates/TwoAgents", "substitutions": { "scenario.py": { "__MODEL__": "gpt-4", "__PROMPT__": "Find 10 papers on explainable or interpretable AI that were submitted to arXiv within the last year. When printing results, include paper titles, authors, dates, and URLs, but not their abstracts." } } }
+{ "id": "old_mslogo_search", "template": "Templates/TwoAgents", "substitutions": { "scenario.py": { "__MODEL__": "gpt-4", "__PROMPT__": "Find Microsoft's logo from 1983, and save it to disk. If searching the web, use Bing with API key stored in os.environ['BING_API_KEY']" } } }
diff --git a/samples/tools/testbed/scenarios/HumanEval/README.md b/samples/tools/testbed/scenarios/HumanEval/README.md
new file mode 100644
index 000000000..b07488658
--- /dev/null
+++ b/samples/tools/testbed/scenarios/HumanEval/README.md
@@ -0,0 +1 @@
+Run `python ../../utils/download_humaneval.py` to populate this folder.
diff --git a/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatFourAgents/coding/my_tests.py b/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatFourAgents/coding/my_tests.py
new file mode 100644
index 000000000..951a40831
--- /dev/null
+++ b/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatFourAgents/coding/my_tests.py
@@ -0,0 +1,10 @@
+# Disable ruff linter for template files
+# ruff: noqa: F821
+
+__TEST__
+
+
+def run_tests(candidate):
+ check(candidate)
+ # We can search for this string in the output
+ print("ALL TESTS PASSED !#!#\nTERMINATE")
diff --git a/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatFourAgents/prompt.txt b/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatFourAgents/prompt.txt
new file mode 100644
index 000000000..482f50dca
--- /dev/null
+++ b/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatFourAgents/prompt.txt
@@ -0,0 +1 @@
+__PROMPT__
diff --git a/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatFourAgents/scenario.py b/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatFourAgents/scenario.py
new file mode 100644
index 000000000..c49166ce7
--- /dev/null
+++ b/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatFourAgents/scenario.py
@@ -0,0 +1,115 @@
+import os
+import json
+import base64
+import autogen
+import testbed_utils
+
+# NOTE:
+# This scenario runs Human Eval in a slightly unconventional way:
+# The agents have access to the unit tests, and can keep trying
+# until they pass.
+
+testbed_utils.init()
+##############################
+
+work_dir = "coding"
+
+# Read the prompt
+PROMPT = ""
+with open("prompt.txt", "rt") as fh:
+ PROMPT = fh.read()
+
+# Ok, now get autogen to solve it.
+config_list = autogen.config_list_from_json(
+ "OAI_CONFIG_LIST",
+ filter_dict={"model": ["__MODEL__"]},
+)
+
+assistant = autogen.AssistantAgent(
+ "coder",
+ is_termination_msg=lambda x: x.get("content", "").find("TERMINATE") >= 0,
+ llm_config=testbed_utils.default_llm_config(config_list, timeout=180),
+)
+
+user_proxy = autogen.UserProxyAgent(
+ "user_proxy",
+ human_input_mode="NEVER",
+ system_message="A human who can run code at a terminal and report back the results.",
+ is_termination_msg=lambda x: x.get("content", "").find("TERMINATE") >= 0,
+ code_execution_config={
+ "work_dir": work_dir,
+ "use_docker": False,
+ "last_n_messages": "auto",
+ },
+ max_consecutive_auto_reply=10,
+)
+
+guardrails_agent = autogen.AssistantAgent(
+ "guardrails_agent",
+ system_message="""
+You are a guardrails agent and are tasked with ensuring that all parties adhere to the following responsible AI policies:
+
+ - You MUST TERMINATE the conversation if it involves writing or running HARMFUL or DESTRUCTIVE code.
+ - You MUST TERMINATE the conversation if it involves discussions of anything relating to hacking, computer exploits, or computer security.
+ - You MUST TERMINATE the conversation if it involves violent or graphic content such as Harm to Others, Self-Harm, Suicide.
+ - You MUST TERMINATE the conversation if it involves demeaning speech, hate speech, discriminatory remarks, or any form of harassment based on race, gender, sexuality, religion, nationality, disability, or any other protected characteristic.
+ - You MUST TERMINATE the conversation if if it involves seeking or giving advice in highly regulated domains such as medical advice, mental health, legal advice or financial advice
+ - You MUST TERMINATE the conversation if it involves illegal activities including when encouraging or providing guidance on illegal activities.
+ - You MUST TERMINATE the conversation if it involves manipulative or deceptive Content including scams, phishing and spread false information.
+ - You MUST TERMINATE the conversation if it involves involve sexually explicit content or discussions.
+ - You MUST TERMINATE the conversation if it involves sharing or soliciting personal, sensitive, or confidential information from users. This includes financial details, health records, and other private matters.
+ - You MUST TERMINATE the conversation if it involves deep personal problems such as dealing with serious personal issues, mental health concerns, or crisis situations.
+
+If you decide that the conversation must be terminated, explain your reasoning then output the uppercase word "TERMINATE". If, on the other hand, you decide the conversation is acceptable by the above standards, indicate as much, then ask the other parties to proceed.
+""".strip(),
+ is_termination_msg=lambda x: x.get("content", "").find("TERMINATE") >= 0,
+ llm_config=testbed_utils.default_llm_config(config_list, timeout=180),
+)
+
+distractor_agent = autogen.AssistantAgent(
+ "executive_chef",
+ system_message="You are an executive chef with 28 years of industry experience. You can answer questions about menu planning, meal preparation, and cooking techniques.",
+ is_termination_msg=lambda x: x.get("content", "").find("TERMINATE") >= 0,
+ llm_config=testbed_utils.default_llm_config(config_list, timeout=180),
+)
+
+groupchat = autogen.GroupChat(
+ agents=[user_proxy, assistant, guardrails_agent, distractor_agent],
+ messages=[],
+ speaker_selection_method="__SELECTION_METHOD__",
+ allow_repeat_speaker=False,
+ max_round=12,
+)
+
+manager = autogen.GroupChatManager(
+ groupchat=groupchat,
+ is_termination_msg=lambda x: x.get("content", "").find("TERMINATE") >= 0,
+ llm_config=testbed_utils.default_llm_config(config_list, timeout=180),
+)
+
+user_proxy.initiate_chat(
+ manager,
+ message="""
+The following python code imports the `run_tests(candidate)` function from my_tests.py, and runs
+it on the function `__ENTRY_POINT__`. This will run a set of automated unit tests to verify the
+correct implementation of `__ENTRY_POINT__`. However, `__ENTRY_POINT__` is only partially
+implemented in the code below. Complete the implementation of `__ENTRY_POINT__` and output
+a new stand-alone code block that contains everything needed to run the tests, including: importing
+`my_tests`, calling `run_tests(__ENTRY_POINT__)`, as well as __ENTRY_POINT__'s complete definition,
+such that this code block can be run directly in Python.
+
+```python
+from my_tests import run_tests
+
+"""
+ + PROMPT
+ + """
+
+# Run the unit tests
+run_tests(__ENTRY_POINT__)
+```
+""",
+)
+
+##############################
+testbed_utils.finalize(agents=[assistant, user_proxy, guardrails_agent, distractor_agent, manager])
diff --git a/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatThreeAgents_Distractor/coding/my_tests.py b/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatThreeAgents_Distractor/coding/my_tests.py
new file mode 100644
index 000000000..951a40831
--- /dev/null
+++ b/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatThreeAgents_Distractor/coding/my_tests.py
@@ -0,0 +1,10 @@
+# Disable ruff linter for template files
+# ruff: noqa: F821
+
+__TEST__
+
+
+def run_tests(candidate):
+ check(candidate)
+ # We can search for this string in the output
+ print("ALL TESTS PASSED !#!#\nTERMINATE")
diff --git a/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatThreeAgents_Distractor/prompt.txt b/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatThreeAgents_Distractor/prompt.txt
new file mode 100644
index 000000000..482f50dca
--- /dev/null
+++ b/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatThreeAgents_Distractor/prompt.txt
@@ -0,0 +1 @@
+__PROMPT__
diff --git a/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatThreeAgents_Distractor/scenario.py b/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatThreeAgents_Distractor/scenario.py
new file mode 100644
index 000000000..ef8d33942
--- /dev/null
+++ b/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatThreeAgents_Distractor/scenario.py
@@ -0,0 +1,93 @@
+import os
+import json
+import base64
+import autogen
+import testbed_utils
+
+# NOTE:
+# This scenario runs Human Eval in a slightly unconventional way:
+# The agents have access to the unit tests, and can keep trying
+# until they pass.
+
+testbed_utils.init()
+##############################
+
+work_dir = "coding"
+
+# Read the prompt
+PROMPT = ""
+with open("prompt.txt", "rt") as fh:
+ PROMPT = fh.read()
+
+# Ok, now get autogen to solve it.
+config_list = autogen.config_list_from_json(
+ "OAI_CONFIG_LIST",
+ filter_dict={"model": ["__MODEL__"]},
+)
+
+assistant = autogen.AssistantAgent(
+ "coder",
+ is_termination_msg=lambda x: x.get("content", "").find("TERMINATE") >= 0,
+ llm_config=testbed_utils.default_llm_config(config_list, timeout=180),
+)
+
+user_proxy = autogen.UserProxyAgent(
+ "user_proxy",
+ human_input_mode="NEVER",
+ system_message="A human who can run code at a terminal and report back the results.",
+ is_termination_msg=lambda x: x.get("content", "").find("TERMINATE") >= 0,
+ code_execution_config={
+ "work_dir": work_dir,
+ "use_docker": False,
+ "last_n_messages": "auto",
+ },
+ max_consecutive_auto_reply=10,
+)
+
+distractor_agent = autogen.AssistantAgent(
+ "executive_chef",
+ system_message="You are an executive chef with 28 years of industry experience. You can answer questions about menu planning, meal preparation, and cooking techniques.",
+ is_termination_msg=lambda x: x.get("content", "").find("TERMINATE") >= 0,
+ llm_config=testbed_utils.default_llm_config(config_list, timeout=180),
+)
+
+groupchat = autogen.GroupChat(
+ agents=[user_proxy, assistant, distractor_agent],
+ messages=[],
+ speaker_selection_method="__SELECTION_METHOD__",
+ allow_repeat_speaker=False,
+ max_round=12,
+)
+
+manager = autogen.GroupChatManager(
+ groupchat=groupchat,
+ is_termination_msg=lambda x: x.get("content", "").find("TERMINATE") >= 0,
+ llm_config=testbed_utils.default_llm_config(config_list, timeout=180),
+)
+
+user_proxy.initiate_chat(
+ manager,
+ message="""
+The following python code imports the `run_tests(candidate)` function from my_tests.py, and runs
+it on the function `__ENTRY_POINT__`. This will run a set of automated unit tests to verify the
+correct implementation of `__ENTRY_POINT__`. However, `__ENTRY_POINT__` is only partially
+implemented in the code below. Complete the implementation of `__ENTRY_POINT__` and output
+a new stand-alone code block that contains everything needed to run the tests, including: importing
+`my_tests`, calling `run_tests(__ENTRY_POINT__)`, as well as __ENTRY_POINT__'s complete definition,
+such that this code block can be run directly in Python.
+
+```python
+from my_tests import run_tests
+
+"""
+ + PROMPT
+ + """
+
+# Run the unit tests
+run_tests(__ENTRY_POINT__)
+```
+""",
+)
+
+##############################
+testbed_utils.finalize(agents=[assistant, user_proxy, distractor_agent, manager])
diff --git a/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatThreeAgents_Guardrails/coding/my_tests.py b/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatThreeAgents_Guardrails/coding/my_tests.py
new file mode 100644
index 000000000..951a40831
--- /dev/null
+++ b/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatThreeAgents_Guardrails/coding/my_tests.py
@@ -0,0 +1,10 @@
+# Disable ruff linter for template files
+# ruff: noqa: F821
+
+__TEST__
+
+
+def run_tests(candidate):
+ check(candidate)
+ # We can search for this string in the output
+ print("ALL TESTS PASSED !#!#\nTERMINATE")
diff --git a/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatThreeAgents_Guardrails/prompt.txt b/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatThreeAgents_Guardrails/prompt.txt
new file mode 100644
index 000000000..482f50dca
--- /dev/null
+++ b/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatThreeAgents_Guardrails/prompt.txt
@@ -0,0 +1 @@
+__PROMPT__
diff --git a/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatThreeAgents_Guardrails/scenario.py b/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatThreeAgents_Guardrails/scenario.py
new file mode 100644
index 000000000..258fdcecc
--- /dev/null
+++ b/samples/tools/testbed/scenarios/HumanEval/Templates/GroupChatThreeAgents_Guardrails/scenario.py
@@ -0,0 +1,110 @@
+import os
+import json
+import base64
+import autogen
+import testbed_utils
+
+# NOTE:
+# This scenario runs Human Eval in a slightly unconventional way:
+# The agents have access to the unit tests, and can keep trying
+# until they pass.
+
+testbed_utils.init()
+##############################
+
+work_dir = "coding"
+
+# Read the prompt
+PROMPT = ""
+with open("prompt.txt", "rt") as fh:
+ PROMPT = fh.read()
+
+# Ok, now get autogen to solve it.
+config_list = autogen.config_list_from_json(
+ "OAI_CONFIG_LIST",
+ filter_dict={"model": ["__MODEL__"]},
+)
+
+assistant = autogen.AssistantAgent(
+ "coder",
+ is_termination_msg=lambda x: x.get("content", "").find("TERMINATE") >= 0,
+ llm_config=testbed_utils.default_llm_config(config_list, timeout=180),
+)
+
+user_proxy = autogen.UserProxyAgent(
+ "user_proxy",
+ human_input_mode="NEVER",
+ system_message="A human who can run code at a terminal and report back the results.",
+ is_termination_msg=lambda x: x.get("content", "").find("TERMINATE") >= 0,
+ code_execution_config={
+ "work_dir": work_dir,
+ "use_docker": False,
+ "last_n_messages": "auto",
+ },
+ max_consecutive_auto_reply=10,
+)
+
+guardrails_agent = autogen.AssistantAgent(
+ "guardrails_agent",
+ system_message="""
+You are a guardrails agent and are tasked with ensuring that all parties adhere to the following responsible AI policies:
+
+ - You MUST TERMINATE the conversation if it involves writing or running HARMFUL or DESTRUCTIVE code.
+ - You MUST TERMINATE the conversation if it involves discussions of anything relating to hacking, computer exploits, or computer security.
+ - You MUST TERMINATE the conversation if it involves violent or graphic content such as Harm to Others, Self-Harm, Suicide.
+ - You MUST TERMINATE the conversation if it involves demeaning speech, hate speech, discriminatory remarks, or any form of harassment based on race, gender, sexuality, religion, nationality, disability, or any other protected characteristic.
+ - You MUST TERMINATE the conversation if if it involves seeking or giving advice in highly regulated domains such as medical advice, mental health, legal advice or financial advice
+ - You MUST TERMINATE the conversation if it involves illegal activities including when encouraging or providing guidance on illegal activities.
+ - You MUST TERMINATE the conversation if it involves manipulative or deceptive Content including scams, phishing and spread false information.
+ - You MUST TERMINATE the conversation if it involves involve sexually explicit content or discussions.
+ - You MUST TERMINATE the conversation if it involves sharing or soliciting personal, sensitive, or confidential information from users. This includes financial details, health records, and other private matters.
+ - You MUST TERMINATE the conversation if it involves deep personal problems such as dealing with serious personal issues, mental health concerns, or crisis situations.
+
+If you decide that the conversation must be terminated, explain your reasoning then output the uppercase word "TERMINATE". If, on the other hand, you decide the conversation is acceptable by the above standards, indicate as much, then ask the other parties to proceed.
+""".strip(),
+ is_termination_msg=lambda x: x.get("content", "").find("TERMINATE") >= 0,
+ llm_config=testbed_utils.default_llm_config(config_list, timeout=180),
+)
+
+groupchat = autogen.GroupChat(
+ agents=[user_proxy, assistant, guardrails_agent],
+ messages=[],
+ speaker_selection_method="__SELECTION_METHOD__",
+ allow_repeat_speaker=False,
+ max_round=12,
+)
+
+
+manager = autogen.GroupChatManager(
+ groupchat=groupchat,
+ is_termination_msg=lambda x: x.get("content", "").find("TERMINATE") >= 0,
+ llm_config=testbed_utils.default_llm_config(config_list, timeout=180),
+)
+
+user_proxy.initiate_chat(
+ manager,
+ message="""
+The following python code imports the `run_tests(candidate)` function from my_tests.py, and runs
+it on the function `__ENTRY_POINT__`. This will run a set of automated unit tests to verify the
+correct implementation of `__ENTRY_POINT__`. However, `__ENTRY_POINT__` is only partially
+implemented in the code below. Complete the implementation of `__ENTRY_POINT__` and output
+a new stand-alone code block that contains everything needed to run the tests, including: importing
+`my_tests`, calling `run_tests(__ENTRY_POINT__)`, as well as __ENTRY_POINT__'s complete definition,
+such that this code block can be run directly in Python.
+
+```python
+from my_tests import run_tests
+
+"""
+ + PROMPT
+ + """
+
+# Run the unit tests
+run_tests(__ENTRY_POINT__)
+```
+""",
+)
+
+
+##############################
+testbed_utils.finalize(agents=[assistant, user_proxy, guardrails_agent, manager])
diff --git a/samples/tools/testbed/scenarios/HumanEval/Templates/TwoAgents/coding/my_tests.py b/samples/tools/testbed/scenarios/HumanEval/Templates/TwoAgents/coding/my_tests.py
new file mode 100644
index 000000000..951a40831
--- /dev/null
+++ b/samples/tools/testbed/scenarios/HumanEval/Templates/TwoAgents/coding/my_tests.py
@@ -0,0 +1,10 @@
+# Disable ruff linter for template files
+# ruff: noqa: F821
+
+__TEST__
+
+
+def run_tests(candidate):
+ check(candidate)
+ # We can search for this string in the output
+ print("ALL TESTS PASSED !#!#\nTERMINATE")
diff --git a/samples/tools/testbed/scenarios/HumanEval/Templates/TwoAgents/prompt.txt b/samples/tools/testbed/scenarios/HumanEval/Templates/TwoAgents/prompt.txt
new file mode 100644
index 000000000..482f50dca
--- /dev/null
+++ b/samples/tools/testbed/scenarios/HumanEval/Templates/TwoAgents/prompt.txt
@@ -0,0 +1 @@
+__PROMPT__
diff --git a/samples/tools/testbed/scenarios/human_eval_two_agents.py b/samples/tools/testbed/scenarios/HumanEval/Templates/TwoAgents/scenario.py
similarity index 62%
rename from samples/tools/testbed/scenarios/human_eval_two_agents.py
rename to samples/tools/testbed/scenarios/HumanEval/Templates/TwoAgents/scenario.py
index 536bf5fe7..d47a09458 100644
--- a/samples/tools/testbed/scenarios/human_eval_two_agents.py
+++ b/samples/tools/testbed/scenarios/HumanEval/Templates/TwoAgents/scenario.py
@@ -14,26 +14,10 @@ testbed_utils.init()
work_dir = "coding"
-# These come formatted as Base64 to avoid conflicting with the triple-quotes
-TESTS = base64.b64decode("__TEST_BASE64__").decode("utf-8")
-PROMPT = base64.b64decode("__PROMPT_BASE64__").decode("utf-8")
-
-# Write the tests to a file so that the agents can access them
-if not os.path.isdir(work_dir):
- os.mkdir(work_dir)
-with open(os.path.join(work_dir, "my_tests.py"), "wt") as fh:
- fh.write(
- TESTS
- + """
-
-
-def run_tests(candidate):
- check(candidate)
- # We can search for this string in the output
- print("ALL TESTS PASSED !#!#\\nTERMINATE")
-"""
- )
-
+# Read the prompt
+PROMPT = ""
+with open("prompt.txt", "rt") as fh:
+ PROMPT = fh.read()
# Ok, now get autogen to solve it.
config_list = autogen.config_list_from_json(
@@ -43,13 +27,14 @@ config_list = autogen.config_list_from_json(
assistant = autogen.AssistantAgent(
"assistant",
- is_termination_msg=lambda x: x.get("content", "").rstrip().find("TERMINATE") >= 0,
+ is_termination_msg=lambda x: x.get("content", "").find("TERMINATE") >= 0,
llm_config=testbed_utils.default_llm_config(config_list, timeout=180),
)
+
user_proxy = autogen.UserProxyAgent(
"user_proxy",
human_input_mode="NEVER",
- is_termination_msg=lambda x: x.get("content", "").rstrip().find("TERMINATE") >= 0,
+ is_termination_msg=lambda x: x.get("content", "").find("TERMINATE") >= 0,
code_execution_config={
"work_dir": work_dir,
"use_docker": False,
@@ -57,6 +42,7 @@ user_proxy = autogen.UserProxyAgent(
max_consecutive_auto_reply=10,
default_auto_reply="TERMINATE",
)
+
user_proxy.initiate_chat(
assistant,
message="""
@@ -64,25 +50,22 @@ The following python code imports the `run_tests(candidate)` function from my_te
it on the function `__ENTRY_POINT__`. This will run a set of automated unit tests to verify the
correct implementation of `__ENTRY_POINT__`. However, `__ENTRY_POINT__` is only partially
implemented in the code below. Complete the implementation of `__ENTRY_POINT__` and output
-a new stand-alone code block that contains everything needed run the tests, including: importing
-`my_tests`, calling `run_tests(__ENTRY_POINT__)`, as well as __ENTRY_POINT__'s comepelte definition,
-such that this code block can be run direcly in Python.
+a new stand-alone code block that contains everything needed to run the tests, including: importing
+`my_tests`, calling `run_tests(__ENTRY_POINT__)`, as well as __ENTRY_POINT__'s complete definition,
+such that this code block can be run directly in Python.
```python
from my_tests import run_tests
-
"""
+ PROMPT
+ """
-
# Run the unit tests
run_tests(__ENTRY_POINT__)
```
""",
)
-
##############################
testbed_utils.finalize(agents=[assistant, user_proxy])
diff --git a/samples/tools/testbed/scenarios/default_two_agents.jsonl b/samples/tools/testbed/scenarios/default_two_agents.jsonl
deleted file mode 100644
index 4da04167f..000000000
--- a/samples/tools/testbed/scenarios/default_two_agents.jsonl
+++ /dev/null
@@ -1,6 +0,0 @@
-{ "id": "two_agent_stocks_gpt4", "template": "default_two_agents.py", "values": { "__MODEL__": "gpt-4", "__PROMPT__": "Plot and save to disk a chart of NVDA and TESLA stock price YTD." } }
-{ "id": "two_agent_stocks_gpt35", "template": "default_two_agents.py", "values": { "__MODEL__": "gpt-3.5-turbo-16k", "__PROMPT__": "Plot and save to disk a chart of NVDA and TESLA stock price YTD." } }
-{ "id": "two_agent_arxiv_search_gpt4", "template": "default_two_agents.py", "values": { "__MODEL__": "gpt-4", "__PROMPT__": "Find 10 papers on explainable or interpretable AI that were submitted to arXiv within the last year. When printing results, include paper titles, authors, dates, and URLs, but not their abstracts." } }
-{ "id": "two_agent_arxiv_search_gpt35", "template": "default_two_agents.py", "values": { "__MODEL__": "gpt-3.5-turbo-16k", "__PROMPT__": "Find 10 papers on explainable or interpretable AI that were submitted to arXiv within the last year. When printing results, include paper titles, authors, dates, and URLs, but not their abstracts." } }
-{ "id": "two_agent_mslogo_search_gpt4", "template": "default_two_agents.py", "values": { "__MODEL__": "gpt-4", "__PROMPT__": "Find Microsoft's logo from 1983, and save it to disk. If searching the web, use Bing with API key stored in os.environ['BING_API_KEY']" } }
-{ "id": "two_agent_mslogo_search_gpt35", "template": "default_two_agents.py", "values": { "__MODEL__": "gpt-3.5-turbo-16k", "__PROMPT__": "Find Microsoft's logo from 1983, and save it to disk. If searching the web, use Bing with the API key stored in os.environ['BING_API_KEY']" } }
diff --git a/samples/tools/testbed/utils/collate_human_eval.py b/samples/tools/testbed/utils/collate_human_eval.py
index ed83bb22b..19dcaac27 100644
--- a/samples/tools/testbed/utils/collate_human_eval.py
+++ b/samples/tools/testbed/utils/collate_human_eval.py
@@ -1,11 +1,7 @@
import os
-import errno
-import shutil
-import subprocess
import json
+import re
import sys
-import time
-import pathlib
import argparse
@@ -34,9 +30,8 @@ def collate(results_dir):
with open(console_log, "rt") as fh:
content = fh.read()
if "ALL TESTS PASSED !#!#" in content:
- results.append(
- str(content.count("assistant (to user_proxy):"))
- ) # The number of assistant replies (which is also equal to the number of GPT calls in this case)
+ # Ideally we would have a more distinctive pattern.
+ results.append(str(len(re.findall(r"\n(.*?) \(to (.*?)\)\:\n", content))))
else:
results.append("-1")
diff --git a/samples/tools/testbed/utils/download_humaneval.py b/samples/tools/testbed/utils/download_humaneval.py
index faf6c3c3b..c967b5342 100644
--- a/samples/tools/testbed/utils/download_humaneval.py
+++ b/samples/tools/testbed/utils/download_humaneval.py
@@ -10,58 +10,110 @@ import json
import os
import base64
+URL = "https://github.com/openai/human-eval/raw/master/data/HumanEval.jsonl.gz"
-script_path = os.path.realpath(__file__)
-script_name = os.path.basename(script_path)
-script_dir = os.path.dirname(script_path)
+SCRIPT_PATH = os.path.realpath(__file__)
+SCRIPT_NAME = os.path.basename(SCRIPT_PATH)
+SCRIPT_DIR = os.path.dirname(SCRIPT_PATH)
-# Directory where scenarios are stored
-scenarios_dir = os.path.realpath(os.path.join(script_dir, os.path.pardir, "scenarios"))
-print("Saving HumanEval scenarios to: " + scenarios_dir)
+# A selected subset of HumanEval problems to work with during development
+REDUCED_SET = [
+ "HumanEval/2",
+ "HumanEval/26",
+ "HumanEval/32",
+ "HumanEval/33",
+ "HumanEval/36",
+ "HumanEval/38",
+ "HumanEval/41",
+ "HumanEval/50",
+ "HumanEval/56",
+ "HumanEval/65",
+ "HumanEval/67",
+ "HumanEval/84",
+ "HumanEval/85",
+ "HumanEval/86",
+ "HumanEval/89",
+ "HumanEval/99",
+ "HumanEval/104",
+ "HumanEval/113",
+ "HumanEval/115",
+ "HumanEval/120",
+ "HumanEval/124",
+ "HumanEval/126",
+ "HumanEval/132",
+ "HumanEval/135",
+ "HumanEval/140",
+ "HumanEval/146",
+]
-# URL of the file to download
-url = "https://github.com/openai/human-eval/raw/master/data/HumanEval.jsonl.gz"
+def download_human_eval():
+ """Download the HumanEval dataset, un-gzips it, and returns a list of its parsed JSON objects."""
-# Send a HTTP request to the URL of the file
-response = requests.get(url)
+ # Send a HTTP request to the URL of the file
+ response = requests.get(URL)
-# Ensure we raise an error if the download failed
-response.raise_for_status()
+ # Ensure we raise an error if the download failed
+ response.raise_for_status()
-# Create a BytesIO object from the response content
-buffer = io.BytesIO(response.content)
+ # Create a BytesIO object from the response content
+ buffer = io.BytesIO(response.content)
-# Create a scenario file
-fh_gpt4 = open(os.path.join(scenarios_dir, "human_eval_two_agents_gpt4.jsonl"), "wt")
-fh_gpt35 = open(os.path.join(scenarios_dir, "human_eval_two_agents_gpt35.jsonl"), "wt")
+ # Read the file, line by line, populating a list of parsed JSON objects
+ results = []
+ with gzip.GzipFile(fileobj=buffer) as f_in:
+ for line in f_in:
+ # Parse each line as JSON
+ results.append(json.loads(line))
-# Open the buffer as a .gz file and read it line by line
-with gzip.GzipFile(fileobj=buffer) as f_in:
- for line in f_in:
- # Parse each line as JSON
- data = json.loads(line)
- print("Converting: " + data["task_id"])
+ return results
- # Write the GPT-4 scenario
- # Prompts and tests are saved in base 64 to greatly simplify escaping them as they
- # move through the various formats and scripts. I welcome a better, more readable, alternative.
- record = {
- "id": data["task_id"].replace("/", "_"),
- "template": "human_eval_two_agents.py",
- "values": {
- "__MODEL__": "gpt-4",
- "__PROMPT_BASE64__": base64.b64encode(data["prompt"].encode("utf-8")).decode("utf-8"),
- "__ENTRY_POINT__": data["entry_point"],
- "__TEST_BASE64__": base64.b64encode(data["test"].encode("utf-8")).decode("utf-8"),
- },
- }
- fh_gpt4.write(json.dumps(record).strip() + "\n")
- # Write the GPT 3.5 Version
- record["values"]["__MODEL__"] = "gpt-3.5-turbo-16k"
- fh_gpt35.write(json.dumps(record).strip() + "\n")
+def create_jsonl(name, tasks, template, model):
+ """Creates a JSONL scenario file with a given name, list of HumanEval tasks, template path, and model."""
+ scenarios_dir = os.path.realpath(os.path.join(SCRIPT_DIR, os.path.pardir, "scenarios", "HumanEval"))
-fh_gpt4.close()
-fh_gpt35.close()
+ with open(os.path.join(scenarios_dir, name + ".jsonl"), "wt") as fh:
+ for task in tasks:
+ print(f"Converting: [{name}] {task['task_id']}")
+
+ record = {
+ "id": task["task_id"].replace("/", "_"),
+ "template": template,
+ "substitutions": {
+ "scenario.py": {
+ "__MODEL__": model,
+ "__ENTRY_POINT__": task["entry_point"],
+ "__SELECTION_METHOD__": "auto",
+ },
+ "prompt.txt": {"__PROMPT__": task["prompt"]},
+ "coding/my_tests.py": {"__TEST__": task["test"]},
+ },
+ }
+
+ fh.write(json.dumps(record).strip() + "\n")
+
+
+###############################################################################
+if __name__ == "__main__":
+ human_eval = download_human_eval()
+ reduced_human_eval = [t for t in human_eval if t["task_id"] in REDUCED_SET]
+
+ models = {
+ "gpt4": "gpt-4",
+ "gpt35": "gpt-3.5-turbo-16k",
+ }
+
+ templates = {
+ "two_agents": "Templates/TwoAgents",
+ "gc3_distractor": "Templates/GroupChatThreeAgents_Distractor",
+ "gc3_guardrails": "Templates/GroupChatThreeAgents_Guardrails",
+ "gc4": "Templates/GroupChatFourAgents",
+ }
+
+ # Create the various combinations of [models] x [templates]
+ for m in models.items():
+ for t in templates.items():
+ create_jsonl(f"human_eval_{t[0]}_{m[0]}", human_eval, t[1], m[1])
+ create_jsonl(f"r_human_eval_{t[0]}_{m[0]}", reduced_human_eval, t[1], m[1])