Skip to content

A programming framework for agentic AI

Teamone webarena agents fully implemented. (#276)

afourney25b9a9132892
diff --git a/python/benchmarks/GAIA/ENV.json.sample b/python/benchmarks/GAIA/ENV.json.sample
index 2c26d1826..468df6813 100644
--- a/python/benchmarks/GAIA/ENV.json.sample
+++ b/python/benchmarks/GAIA/ENV.json.sample
@@ -1,6 +1,6 @@
{
"CHAT_COMPLETION_PROVIDER": "azure",
- "CHAT_COMPLETION_KWARGS_JSON": "{\"api_version\": \"2024-05-01-preview\", \"azure_endpoint\": \"YOUR_ENDPOINT_HERE\", \"model_capabilities\": {\"function_calling\": true, \"json_output\": true, \"vision\": true}, \"azure_ad_token_provider\": \"DEFAULT\", \"model\": \"gpt-4o-2024-05-13\"}",
+ "CHAT_COMPLETION_KWARGS_JSON": "{\"api_version\": \"2024-05-01-preview\", \"azure_endpoint\": \"YOUR_ENDPOINT_HERE\", \"model_capabilities\": {\"function_calling\": true, \"json_output\": true, \"vision\": true}, \"model\": \"gpt-4o-2024-05-13\"}",
"BING_API_KEY": "YOUR_KEY_KEY",
"HOMEPAGE": "https://www.bing.com/",
"WEB_SURFER_DEBUG_DIR": "/autogen/debug"
diff --git a/python/benchmarks/GAIA/Templates/TeamOne/scenario.py b/python/benchmarks/GAIA/Templates/TeamOne/scenario.py
index 20a0ec7f1..2a2d5a17a 100644
--- a/python/benchmarks/GAIA/Templates/TeamOne/scenario.py
+++ b/python/benchmarks/GAIA/Templates/TeamOne/scenario.py
@@ -59,8 +59,8 @@ ADDITIONALLY, your FINAL ANSWER MUST adhere to any formatting instructions speci
If you are asked for a number, express it numerically (i.e., with digits rather than words), don't use commas, and don't include units such as $ or percent signs unless specified otherwise.
If you are asked for a string, don't use articles or abbreviations (e.g. for cities), unless specified otherwise. Don't output any final sentence punctuation such as '.', '!', or '?'.
If you are asked for a comma separated list, apply the above rules depending on whether the elements are numbers or strings.
+If you are unable to determine the final answer, output 'FINAL ANSWER: Unable to determine'
""",
-#If you are unable to determine the final answer, output 'FINAL ANSWER: Unable to determine'
source=source,
)
)
diff --git a/python/benchmarks/WebArena/.gitignore b/python/benchmarks/WebArena/.gitignore
new file mode 100644
index 000000000..8e419f867
--- /dev/null
+++ b/python/benchmarks/WebArena/.gitignore
@@ -0,0 +1,2 @@
+Results
+ENV.json
diff --git a/python/benchmarks/WebArena/ENV.sample.json b/python/benchmarks/WebArena/ENV.sample.json
new file mode 100644
index 000000000..0b8311b13
--- /dev/null
+++ b/python/benchmarks/WebArena/ENV.sample.json
@@ -0,0 +1,28 @@
+{
+ "CHAT_COMPLETION_PROVIDER": "azure",
+ "CHAT_COMPLETION_KWARGS_JSON": "{\"api_version\": \"2024-05-01-preview\", \"azure_endpoint\": \"YOUR_ENDPOINT_HERE\", \"model_capabilities\": {\"function_calling\": true, \"json_output\": true, \"vision\": true}, \"model\": \"gpt-4o-2024-05-13\"}",
+
+ "SHOPPING": "",
+ "SHOPPING_ADMIN": "",
+ "REDDIT": "",
+ "GITLAB": "",
+ "MAP": "",
+ "WIKIPEDIA": "",
+ "HOMEPAGE": "",
+
+ "REDDIT_USERNAME": "",
+ "REDDIT_PASSWORD": "",
+
+ "GITLAB_USERNAME": "",
+ "GITLAB_PASSWORD": "",
+
+ "SHOPPING_USERNAME": "",
+ "SHOPPING_PASSWORD": "",
+
+ "SHOPPING_ADMIN_USERNAME": "",
+ "SHOPPING_ADMIN_PASSWORD": "",
+
+ "WEB_SURFER_DEBUG_DIR": "/autogen/debug",
+
+ "OPENAI_API_KEY": ""
+}
diff --git a/python/benchmarks/WebArena/Scripts/custom_tabulate.py b/python/benchmarks/WebArena/Scripts/custom_tabulate.py
new file mode 100644
index 000000000..daedc2786
--- /dev/null
+++ b/python/benchmarks/WebArena/Scripts/custom_tabulate.py
@@ -0,0 +1,15 @@
+import os
+import sys
+from autogenbench.tabulate_cmd import default_tabulate, default_scorer
+
+
+def scorer(instance_dir, success_strings=["FINAL SCORE: 1"]):
+ return default_scorer(instance_dir, success_strings=success_strings)
+
+
+def main(args):
+ default_tabulate(args, scorer=scorer)
+
+
+if __name__ == "__main__" and __package__ is None:
+ main(sys.argv)
diff --git a/python/benchmarks/WebArena/Scripts/init_tasks.py b/python/benchmarks/WebArena/Scripts/init_tasks.py
new file mode 100644
index 000000000..5ba3fd4d0
--- /dev/null
+++ b/python/benchmarks/WebArena/Scripts/init_tasks.py
@@ -0,0 +1,122 @@
+#
+# Run this file to download the human_eval dataset, and create a corresponding testbed scenario:
+# (default: ../scenarios/human_eval_two_agents_gpt4.jsonl and ./scenarios/human_eval_two_agents_gpt35.jsonl)
+#
+
+import requests
+import tarfile
+import hashlib
+import io
+import json
+import os
+import re
+import sys
+
+URL = "https://raw.githubusercontent.com/web-arena-x/webarena/main/config_files/test.raw.json"
+
+SCRIPT_PATH = os.path.realpath(__file__)
+SCRIPT_NAME = os.path.basename(SCRIPT_PATH)
+SCRIPT_DIR = os.path.dirname(SCRIPT_PATH)
+
+SCENARIO_DIR = os.path.realpath(os.path.join(SCRIPT_DIR, os.path.pardir))
+TEMPLATES_DIR = os.path.join(SCENARIO_DIR, "Templates")
+TASKS_DIR = os.path.join(SCENARIO_DIR, "Tasks")
+DOWNLOADS_DIR = os.path.join(SCENARIO_DIR, "Downloads")
+
+
+def download():
+ """Download the WebArena dataset (if not already downloaded).
+ Return a JSON list of problem instances."""
+
+ if not os.path.isdir(DOWNLOADS_DIR):
+ os.mkdir(DOWNLOADS_DIR)
+
+ json_file = os.path.join(DOWNLOADS_DIR, "test.raw.json")
+
+ if not os.path.isfile(json_file):
+ # Send a HTTP request to the URL
+ response = requests.get(URL, stream=True)
+ response.raise_for_status()
+
+ # If the HTTP request returns a status code 200, proceed
+ with open(json_file, "wb") as fh:
+ for chunk in response.iter_content(chunk_size=512):
+ fh.write(chunk)
+
+ # Load the problems
+ problems = None
+ with open(json_file, "rb") as fh:
+ problems = json.load(fh)
+ return problems
+
+
+def create_jsonl(name, tasks, template):
+ """Creates a JSONL scenario file with a given name, dictionary of MATH problems, and template path."""
+
+ # Create a task directory if it doesn't exist
+ if not os.path.isdir(TASKS_DIR):
+ os.mkdir(TASKS_DIR)
+
+ # Create the jsonl file
+ prompt_fields = ["task_id", "intent_template_id", "sites", "require_login", "start_url", "geolocation", "intent"]
+ with open(os.path.join(TASKS_DIR, name + ".jsonl"), "wt") as fh:
+ for task in tasks:
+ print(f"Converting: {name}, {task['task_id']}")
+
+ task_prompt = {}
+ for field in prompt_fields:
+ task_prompt[field] = task[field]
+
+ record = {
+ "id": str(task["task_id"]),
+ "template": [os.path.join(TEMPLATES_DIR, "Common"), template],
+ "substitutions": {
+ "task_prompt.json.txt": {"__TASK_PROMPT__": json.dumps(task_prompt, indent=4)},
+ "full_task.json.txt": {"__FULL_TASK__": json.dumps(task, indent=4)},
+ },
+ }
+
+ fh.write(json.dumps(record).strip() + "\n")
+
+
+###############################################################################
+def main():
+ tasks = download()
+
+ # list all directories in the Templates directory
+ # and populate a dictionary with the name and path
+ templates = {}
+ for entry in os.scandir(TEMPLATES_DIR):
+ if entry.is_dir():
+ if entry.name == "Common": # Skip the common template, which will be included in all
+ continue
+ templates[re.sub(r"\s", "", entry.name)] = entry.path
+
+ # Divide the tasks by their websites and if they are validation or test
+ page_groups = dict()
+ for task in tasks:
+
+ # We don't know how the intent ids are distributed, so hash them to get a uniform distribution
+ template_hash = hashlib.md5(str(task["intent_template_id"]).encode("utf-8")).hexdigest()
+
+ # The full hash will consist of 32 hexadecimal digits. We can get a 50/50 split by checking if the first digit is in the range (0-7) vs (8-F)
+ task_set = "validation" if template_hash[0] in "01234567" else "test"
+
+ key = task["sites"][0]
+ if len(task["sites"]) > 1:
+ key = "several_sites"
+ key = task_set + "_" + key
+
+ # key = "__".join(sorted([s for s in task["sites"]]))
+ if key not in page_groups:
+ page_groups[key] = list()
+ page_groups[key].append(task)
+
+ # Create the json files
+ for t in templates.items():
+ for pg in page_groups:
+ create_jsonl(f"webarena__{pg}_{t[0]}", page_groups[pg], t[1])
+
+
+if __name__ == "__main__" and __package__ is None:
+ main()
diff --git a/python/benchmarks/WebArena/Templates/Common/evaluation_harness/ATTRIBUTION b/python/benchmarks/WebArena/Templates/Common/evaluation_harness/ATTRIBUTION
new file mode 100644
index 000000000..0713904fb
--- /dev/null
+++ b/python/benchmarks/WebArena/Templates/Common/evaluation_harness/ATTRIBUTION
@@ -0,0 +1,28 @@
+The contents of this `evaluation_harness` folder are adapted from:
+
+ https://github.com/web-arena-x/webarena
+
+under the following license:
+
+=========================================================================================================
+
+Copyright (c) 2024 Jing Yu Koh, Robert Lo, Lawrence Jang, Vikram Duvvur, Ming Chong Lim, and Po-Yu Huang
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/python/benchmarks/WebArena/Templates/Common/evaluation_harness/__init__.py b/python/benchmarks/WebArena/Templates/Common/evaluation_harness/__init__.py
new file mode 100644
index 000000000..e942c1066
--- /dev/null
+++ b/python/benchmarks/WebArena/Templates/Common/evaluation_harness/__init__.py
@@ -0,0 +1,6 @@
+from .evaluators import *
+from .helper_functions import (
+ shopping_get_latest_order_url,
+ shopping_get_sku_latest_review_author,
+ shopping_get_sku_latest_review_rating,
+)
diff --git a/python/benchmarks/WebArena/Templates/Common/evaluation_harness/env_config.py b/python/benchmarks/WebArena/Templates/Common/evaluation_harness/env_config.py
new file mode 100644
index 000000000..ed84ae473
--- /dev/null
+++ b/python/benchmarks/WebArena/Templates/Common/evaluation_harness/env_config.py
@@ -0,0 +1,90 @@
+# websites domain
+import os
+
+REDDIT = os.environ.get("REDDIT", "")
+SHOPPING = os.environ.get("SHOPPING", "")
+SHOPPING_ADMIN = os.environ.get("SHOPPING_ADMIN", "")
+GITLAB = os.environ.get("GITLAB", "")
+WIKIPEDIA = os.environ.get("WIKIPEDIA", "")
+MAP = os.environ.get("MAP", "")
+HOMEPAGE = os.environ.get("HOMEPAGE", "")
+
+REDDIT_USERNAME = os.environ.get("REDDIT_USERNAME", "")
+REDDIT_PASSWORD = os.environ.get("REDDIT_PASSWORD", "")
+
+GITLAB_USERNAME = os.environ.get("GITLAB_USERNAME", "")
+GITLAB_PASSWORD = os.environ.get("GITLAB_PASSWORD", "")
+
+SHOPPING_USERNAME = os.environ.get("SHOPPING_USERNAME", "")
+SHOPPING_PASSWORD = os.environ.get("SHOPPING_PASSWORD", "")
+
+SHOPPING_ADMIN_USERNAME = os.environ.get("SHOPPING_ADMIN_USERNAME", "")
+SHOPPING_ADMIN_PASSWORD = os.environ.get("SHOPPING_ADMIN_PASSWORD", "")
+
+assert REDDIT and SHOPPING and SHOPPING_ADMIN and GITLAB and WIKIPEDIA and MAP and HOMEPAGE, (
+ "Please setup the URLs to each site. Current: \n"
+ + f"Reddit: {REDDIT}\n"
+ + f"Shopping: {SHOPPING}\n"
+ + f"Shopping Admin: {SHOPPING_ADMIN}\n"
+ + f"Gitlab: {GITLAB}\n"
+ + f"Wikipedia: {WIKIPEDIA}\n"
+ + f"Map: {MAP}\n"
+ + f"Homepage: {HOMEPAGE}\n"
+)
+
+ACCOUNTS = {
+ "reddit": {"username": REDDIT_USERNAME, "password": REDDIT_PASSWORD},
+ "gitlab": {"username": GITLAB_USERNAME, "password": GITLAB_PASSWORD},
+ "shopping": {"username": SHOPPING_USERNAME, "password": SHOPPING_PASSWORD},
+ "shopping_admin": {"username": SHOPPING_ADMIN_USERNAME, "password": SHOPPING_ADMIN_PASSWORD},
+ "shopping_site_admin": {"username": SHOPPING_ADMIN_USERNAME, "password": SHOPPING_ADMIN_PASSWORD},
+}
+
+URL_MAPPINGS = {
+ REDDIT: "http://reddit.com",
+ SHOPPING: "http://onestopmarket.com",
+ SHOPPING_ADMIN: "http://luma.com/admin",
+ GITLAB: "http://gitlab.com",
+ WIKIPEDIA: "http://wikipedia.org",
+ MAP: "http://openstreetmap.org",
+ HOMEPAGE: "http://homepage.com",
+}
+
+# ADDED BY MSR Frontiers
+#########################
+SITE_URLS = {
+ "reddit": REDDIT,
+ "gitlab": GITLAB,
+ "shopping": SHOPPING,
+ "shopping_admin": SHOPPING_ADMIN,
+ "shopping_site_admin": SHOPPING_ADMIN,
+ "map": MAP,
+ "wikipedia": WIKIPEDIA,
+}
+
+LOGIN_PROMPTS = {
+ "reddit": f"Type '{REDDIT}' into the address bar to navigate to the site. Click 'Log in', type the username '{ACCOUNTS['reddit']['username']}', and password is '{ACCOUNTS['reddit']['password']}'. Finally click the login button.",
+ "gitlab": f"Type '{GITLAB}' into the address bar to navigate to the site. At the log in prompt, type the username '{ACCOUNTS['gitlab']['username']}', and the password '{ACCOUNTS['gitlab']['password']}'. Finally click the 'Sign in' button.",
+ "shopping": f"Type '{SHOPPING}' into the address bar to navigate to the site. Click 'Sign In' at the top of the page. Enter the Email '{ACCOUNTS['shopping']['username']}', and password '{ACCOUNTS['shopping']['password']}'. Finally click the 'Sign In' button.",
+ "shopping_admin": f"Type '{SHOPPING_ADMIN}' into the address bar to navigate to the site. At the log in prompt, enter the username '{ACCOUNTS['shopping_admin']['username']}', and the password '{ACCOUNTS['shopping_admin']['password']}'. Finally click the 'Sign In' button.",
+}
+
+SITE_DESCRIPTIONS = {
+ "reddit": "a Postmill forum populated with a large sample of data crawled from Reddit. Postmill is similar to Reddit, but the UI is distinct, and 'subreddits' begin with /f/ rather than /r/",
+ "gitlab": "a Gitlab site populated with various programming projects. Gitlab is similar to GitHub, though the UIs are slightly different",
+ "shopping": "an online store built with the Magento open source eCommerce platform",
+ "shopping_admin": "the content management admin portal for an online store running the Magento open source eCommerce software",
+}
+
+
+def url_to_sitename(url):
+ if url.startswith(REDDIT):
+ return "reddit"
+ elif url.startswith(GITLAB):
+ return "gitlab"
+ elif url.startswith(SHOPPING):
+ return "shopping"
+ elif url.startswith(SHOPPING_ADMIN):
+ return "shopping_admin"
+ else:
+ return None
diff --git a/python/benchmarks/WebArena/Templates/Common/evaluation_harness/evaluators.py b/python/benchmarks/WebArena/Templates/Common/evaluation_harness/evaluators.py
new file mode 100644
index 000000000..c94f1d59e
--- /dev/null
+++ b/python/benchmarks/WebArena/Templates/Common/evaluation_harness/evaluators.py
@@ -0,0 +1,381 @@
+"""base class for evaluation"""
+
+# answer string match
+import collections
+import html
+import importlib
+import json
+import time
+import urllib
+from pathlib import Path
+from typing import Any, Tuple, Union, TypedDict, Dict
+
+from beartype import beartype
+from nltk.tokenize import word_tokenize # type: ignore
+from playwright.sync_api import CDPSession, Page
+
+import numpy as np
+import numpy.typing as npt
+
+from .helper_functions import (
+ PseudoPage,
+ gitlab_get_project_memeber_role,
+ llm_fuzzy_match,
+ llm_ua_match,
+ reddit_get_post_url,
+ shopping_get_latest_order_url,
+ shopping_get_sku_latest_review_author,
+ shopping_get_sku_latest_review_rating,
+)
+
+
+# Subset used for evaluation (added by: adamfo)
+#####################################################################
+class Action(TypedDict):
+ answer: str
+
+
+Observation = str | npt.NDArray[np.uint8]
+
+
+class StateInfo(TypedDict):
+ observation: dict[str, Observation]
+ info: Dict[str, Any]
+
+
+Trajectory = list[Union[Action, StateInfo]]
+
+
+def make_answer_trajecotry(answer: str) -> Trajectory:
+ ans = Action()
+ ans["answer"] = answer
+ return [ans]
+
+
+#####################################################################
+class Evaluator(object):
+ def __init__(self, eval_tag: str = "") -> None:
+ self.eval_tag = eval_tag
+
+ @beartype
+ def __call__(
+ self,
+ trajectory: Trajectory,
+ config_file: Path | str,
+ page: Page | PseudoPage,
+ client: CDPSession,
+ azure_config: dict[str, Any] | None = None,
+ ) -> float:
+ raise NotImplementedError
+
+ @staticmethod
+ def get_last_action(trajectory: Trajectory) -> Action:
+ try:
+ # is_bearable(trajectory[-1], Action)
+ last_action = trajectory[-1]
+ except Exception:
+ raise ValueError("The last element of trajectory should be an action, add a fake stop action if needed")
+
+ return last_action # type: ignore[return-value]
+
+ @staticmethod
+ def get_last_state(trajectory: Trajectory) -> StateInfo:
+ try:
+ # is_bearable(trajectory[-2], StateInfo)
+ last_state = trajectory[-2]
+ except Exception:
+ raise ValueError(
+ "The second last element of trajectory should be a state, add a fake stop action if needed"
+ )
+
+ return last_state # type: ignore[return-value]
+
+
+class StringEvaluator(Evaluator):
+ """Check whether the answer is correct with:
+ exact match: the answer is exactly the same as the reference answer
+ must include: each phrase in the reference answer must be included in the answer
+ fuzzy match: the answer is similar to the reference answer, using LLM judge
+ """
+
+ @staticmethod
+ @beartype
+ def clean_answer(answer: str) -> str:
+ answer = answer.strip()
+ if answer.startswith("'") and answer.endswith("'"):
+ answer = answer[1:-1]
+ elif answer.startswith('"') and answer.endswith('"'):
+ answer = answer[1:-1]
+ return answer.lower()
+
+ @staticmethod
+ @beartype
+ def exact_match(ref: str, pred: str) -> float:
+ return float(StringEvaluator.clean_answer(pred) == StringEvaluator.clean_answer(ref))
+
+ @staticmethod
+ @beartype
+ def must_include(ref: str, pred: str, tokenize: bool = False) -> float:
+ clean_ref = StringEvaluator.clean_answer(ref)
+ clean_pred = StringEvaluator.clean_answer(pred)
+ # tokenize the answer if the ref is a single word
+ # prevent false positive (e.g, 0)
+ if tokenize and len(clean_ref) == 1 and len(word_tokenize(clean_ref)) == 1:
+ tok_pred = word_tokenize(clean_pred)
+ return float(clean_ref in tok_pred)
+ else:
+ return float(clean_ref in clean_pred)
+
+ @staticmethod
+ @beartype
+ def fuzzy_match(ref: str, pred: str, intent: str, azure_config: dict[str, Any] | None) -> float:
+ return llm_fuzzy_match(pred, ref, intent, azure_config)
+
+ @staticmethod
+ @beartype
+ def ua_match(ref: str, pred: str, intent: str, azure_config: dict[str, Any] | None) -> float:
+ return llm_ua_match(pred, ref, intent, azure_config)
+
+ def __call__(
+ self,
+ trajectory: Trajectory,
+ config_file: Path | str,
+ page: Page | PseudoPage | None = None,
+ client: CDPSession | None = None,
+ azure_config: dict[str, Any] | None = None,
+ ) -> float:
+ with open(config_file, "r") as f:
+ configs = json.load(f)
+
+ last_action = self.get_last_action(trajectory)
+ pred = self.clean_answer(last_action["answer"])
+
+ score = 1.0
+ for approach, value in configs["eval"]["reference_answers"].items():
+ match approach:
+ case "exact_match":
+ score *= self.exact_match(ref=value, pred=pred)
+
+ case "must_include":
+ assert isinstance(value, list)
+ for must_value in value:
+ score *= self.must_include(
+ ref=must_value,
+ pred=pred,
+ tokenize=(len(value) == 1),
+ )
+ case "fuzzy_match":
+ intent = configs["intent"]
+ if value == "N/A":
+ # if the instruction only asks the model to generate N/A when encountering an unachievable task
+ # without more concrete reasons
+ score *= self.exact_match(ref=value, pred=pred)
+ # if the instruction also asks the model to generate the reason why the task is unachievable
+ # this should be the default as it will prevent false positive N/A`
+ if score != 1:
+ score = 1.0 * self.ua_match(
+ intent=configs["intent"],
+ ref=configs["eval"]["string_note"],
+ pred=pred,
+ azure_config=azure_config,
+ )
+ else:
+ assert isinstance(value, list)
+ for reference in value:
+ score *= self.fuzzy_match(
+ ref=reference, pred=pred, intent=intent, azure_config=azure_config
+ )
+ return score
+
+
+class URLEvaluator(Evaluator):
+ """Check URL matching"""
+
+ @beartype
+ def __call__(
+ self,
+ trajectory: Trajectory,
+ config_file: Path | str,
+ page: Page | PseudoPage,
+ client: CDPSession | None = None,
+ azure_config: dict[str, Any] | None = None,
+ ) -> float:
+ with open(config_file, "r") as f:
+ configs = json.load(f)
+
+ def clean_url(url: str) -> str:
+ url = str(url)
+ url = url.rstrip("/")
+ return url
+
+ def parse_url(url: str) -> tuple[str, dict[str, list[str]]]:
+ """Parse a URL into its base, path, and query components."""
+ parsed_url = urllib.parse.urlparse(url)
+ base_path = parsed_url.netloc + parsed_url.path
+ query = urllib.parse.parse_qs(parsed_url.query)
+ return base_path, query
+
+ def parse_urls(
+ urls: list[str],
+ ) -> tuple[list[str], dict[str, set[str]]]:
+ """Parse a list of URLs."""
+ base_paths = []
+ queries = collections.defaultdict(set)
+ for url in urls:
+ base_path, query = parse_url(url)
+ base_paths.append(base_path)
+ for k, v in query.items():
+ queries[k].update(v)
+ return base_paths, queries
+
+ pred = clean_url(page.url)
+ ref_urls = configs["eval"]["reference_url"].split(" |OR| ")
+ ref_urls = [clean_url(url) for url in ref_urls]
+ matching_rule = configs["eval"].get("url_note", "GOLD in PRED")
+ if matching_rule == "GOLD in PRED":
+ print(f"Pred: {pred}")
+ print(f"Ref: {ref_urls}")
+ ref_base_paths, ref_queries = parse_urls(ref_urls)
+ pred_base_paths, pred_query = parse_url(pred)
+
+ base_score = float(any([ref_base_path in pred_base_paths for ref_base_path in ref_base_paths]))
+ query_score = 1.0
+ for k, possible_values in ref_queries.items():
+ query_score *= float(
+ any(possible_ref_value in pred_query.get(k, []) for possible_ref_value in possible_values)
+ )
+ score = base_score * query_score
+
+ else:
+ raise ValueError(f"Unknown matching rule: {matching_rule}")
+
+ return score
+
+
+class HTMLContentEvaluator(Evaluator):
+ """Check whether the contents appear in the page"""
+
+ @beartype
+ def __call__(
+ self,
+ trajectory: Trajectory,
+ config_file: Path | str,
+ page: Page | PseudoPage,
+ client: CDPSession | None = None,
+ azure_config: dict[str, Any] | None = None,
+ ) -> float:
+ with open(config_file, "r") as f:
+ configs = json.load(f)
+
+ targets = configs["eval"]["program_html"]
+
+ score = 1.0
+ for target in targets:
+ target_url: str = target["url"] # which url to check
+ if target_url.startswith("func"):
+ func = target_url.split("func:")[1]
+ func = func.replace("__last_url__", page.url)
+ target_url = eval(func)
+
+ locator: str = target["locator"] # js element locator
+
+ # navigate to that url
+ if target_url != "last":
+ page.goto(target_url)
+ time.sleep(3) # TODO [shuyanzh]: fix this hard-coded sleep
+
+ # empty, use the full page
+ if not locator.strip():
+ selected_element = page.content()
+ # use JS to select the element
+ elif locator.startswith("document.") or locator.startswith("[...document."):
+ if "prep_actions" in target:
+ try:
+ for prep_action in target["prep_actions"]:
+ page.evaluate(f"() => {prep_action}")
+ except Exception:
+ pass
+ try:
+ selected_element = str(page.evaluate(f"() => {locator}"))
+ if not selected_element:
+ selected_element = ""
+ except Exception:
+ # the page is wrong, return empty
+ selected_element = ""
+ # run program to call API
+ elif locator.startswith("func:"): # a helper function
+ func = locator.split("func:")[1]
+ func = func.replace("__page__", "page")
+ selected_element = eval(func)
+ else:
+ raise ValueError(f"Unknown locator: {locator}")
+
+ selected_element = html.unescape(selected_element)
+
+ if "exact_match" in target["required_contents"]:
+ required_contents = target["required_contents"]["exact_match"]
+ cur_score = StringEvaluator.exact_match(ref=required_contents, pred=selected_element)
+ score *= float(cur_score)
+ # print(f"[exact match] {cur_score}, selected element: {selected_element}, required contents: {required_contents}")
+ elif "must_include" in target["required_contents"]:
+ required_contents = target["required_contents"]["must_include"]
+ assert isinstance(required_contents, list)
+ for content in required_contents:
+ content_or = content.split(" |OR| ")
+ cur_score = any(
+ [
+ StringEvaluator.must_include(
+ ref=content,
+ pred=selected_element,
+ tokenize=False,
+ )
+ for content in content_or
+ ]
+ )
+ score *= float(cur_score)
+ # print(f"[must include] {cur_score}, selected element: {selected_element}, required contents: {content_or}")
+ else:
+ raise ValueError(f"Unknown required_contents: {target['required_contents'].keys()}")
+ return score
+
+
+class EvaluatorComb:
+ def __init__(self, evaluators: list[Evaluator]) -> None:
+ self.evaluators = evaluators
+
+ @beartype
+ def __call__(
+ self,
+ trajectory: Trajectory,
+ config_file: Path | str,
+ page: Page | PseudoPage,
+ client: CDPSession,
+ azure_config: dict[str, Any] | None = None,
+ ) -> float:
+ score = 1.0
+ for evaluator in self.evaluators:
+ cur_score = evaluator(trajectory, config_file, page, client, azure_config)
+ score *= cur_score
+ return score
+
+
+@beartype
+def evaluator_router(config_file: Path | str) -> EvaluatorComb:
+ """Router to get the evaluator class"""
+ with open(config_file, "r") as f:
+ configs = json.load(f)
+
+ eval_types = configs["eval"]["eval_types"]
+ evaluators: list[Evaluator] = []
+ for eval_type in eval_types:
+ match eval_type:
+ case "string_match":
+ evaluators.append(StringEvaluator())
+ case "url_match":
+ evaluators.append(URLEvaluator())
+ case "program_html":
+ evaluators.append(HTMLContentEvaluator())
+ case _:
+ raise ValueError(f"eval_type {eval_type} is not supported")
+
+ return EvaluatorComb(evaluators)
diff --git a/python/benchmarks/WebArena/Templates/Common/evaluation_harness/helper_functions.py b/python/benchmarks/WebArena/Templates/Common/evaluation_harness/helper_functions.py
new file mode 100644
index 000000000..acb874a2a
--- /dev/null
+++ b/python/benchmarks/WebArena/Templates/Common/evaluation_harness/helper_functions.py
@@ -0,0 +1,233 @@
+"""Implements helper functions to assist evaluation cases where other evaluators are not suitable."""
+
+import json
+from typing import Any
+from urllib.parse import urlparse
+
+import requests
+from playwright.sync_api import CDPSession, Page
+
+from .env_config import (
+ ACCOUNTS,
+ GITLAB,
+ MAP,
+ REDDIT,
+ SHOPPING,
+ SHOPPING_ADMIN,
+ WIKIPEDIA,
+)
+
+from .openai_utils import (
+ generate_from_openai_chat_completion,
+)
+
+import autogen
+
+
+def shopping_get_auth_token() -> str:
+ response = requests.post(
+ url=f"{SHOPPING}/rest/default/V1/integration/admin/token",
+ headers={"content-type": "application/json"},
+ data=json.dumps(
+ {
+ "username": ACCOUNTS["shopping_site_admin"]["username"],
+ "password": ACCOUNTS["shopping_site_admin"]["password"],
+ }
+ ),
+ )
+ token: str = response.json()
+ return token
+
+
+def shopping_get_latest_order_url() -> str:
+ """Get the latest order url from the shopping website."""
+
+ header = {
+ "Authorization": f"Bearer {shopping_get_auth_token()}",
+ "Content-Type": "application/json",
+ }
+
+ params = {
+ "searchCriteria[sortOrders][0][field]": "created_at",
+ "searchCriteria[sortOrders][0][direction]": "DESC",
+ "searchCriteria[pageSize]": "1",
+ }
+
+ response = requests.get(f"{SHOPPING}/rest/V1/orders", params=params, headers=header)
+ assert response.status_code == 200
+ response_obj = response.json()["items"][0]
+ order_id = int(response_obj["increment_id"])
+ order_url = f"{SHOPPING}/sales/order/view/order_id/{order_id}/"
+ return order_url
+
+
+def shopping_get_sku_latest_review_author(sku: str) -> str:
+ """Get the latest review for shopping admin."""
+ header = {
+ "Authorization": f"Bearer {shopping_get_auth_token()}",
+ "Content-Type": "application/json",
+ }
+ response = requests.get(f"{SHOPPING}/rest/V1/products/{sku}/reviews", headers=header)
+ assert response.status_code == 200
+ response_obj = response.json()
+ if len(response_obj) == 0:
+ return ""
+ author: str = response_obj[-1]["nickname"]
+ return author
+
+
+def shopping_get_sku_latest_review_rating(sku: str) -> str:
+ """Get the latest review for shopping admin."""
+ header = {
+ "Authorization": f"Bearer {shopping_get_auth_token()}",
+ "Content-Type": "application/json",
+ }
+ response = requests.get(f"{SHOPPING}/rest/V1/products/{sku}/reviews", headers=header)
+ assert response.status_code == 200
+ response_obj = response.json()
+ if len(response_obj) == 0:
+ return ""
+ assert response_obj[0]["ratings"][0]["rating_name"] == "Rating"
+ rating: str = str(response_obj[-1]["ratings"][0]["percent"])
+ return rating
+
+
+def reddit_get_post_url(url: str) -> str:
+ """Get the post url"""
+ # Url is http://domain/f/subreddit/post_id/...
+ # get domain, subreddit, post_id
+ domain = urlparse(url).netloc
+ tok_url = urlparse(url).path.split("/")
+ # not a valid post/comment url, return the url as is
+ if len(tok_url) < 4:
+ return url
+ if tok_url[1] != "f":
+ return url
+ subreddit = urlparse(url).path.split("/")[2]
+ post_id = urlparse(url).path.split("/")[3]
+ scheme = urlparse(url).scheme
+ post_url = f"{scheme}://{domain}/f/{subreddit}/{post_id}/"
+ return post_url
+
+
+def gitlab_get_project_memeber_role(page: Page, account_name: str) -> str:
+ # get the account index
+ try:
+ account_idx = page.evaluate(
+ f"""(() => {{
+ const elements = document.querySelectorAll("td[data-label='Account'] span.gl-avatar-labeled-sublabel");
+ let index = -1; // Default value if not found
+
+ for(let i = 0; i < elements.length; i++) {{
+ if(elements[i].outerText === '@{account_name}') {{
+ index = i;
+ break;
+ }}
+ }}
+
+ return index;
+ }})()"""
+ )
+
+ # get the role
+ role: str = page.evaluate(
+ f"""(() => {{
+ return document.querySelectorAll("td.col-max-role span")[{account_idx}].outerText;
+ }})()"""
+ )
+ except Exception:
+ role = ""
+
+ return role
+
+
+def llm_fuzzy_match(pred: str, reference: str, question: str, azure_config: dict[str, Any] | None) -> float:
+ """Check whether the prediction matches the reference with GPT4-turbo"""
+ messages: list[dict[str, Any]] = []
+ # construct the question to ask
+ message = "Help a teacher to grade the answer of a student given a question. Keep in mind that the student may use different phrasing or wording to answer the question. The goal is to evaluate whether the answer is semantically equivalent to the reference answer.\n"
+ message += f"question: {question}\n"
+ message += f"reference answer: {reference}\n"
+ message += "all the string 'N/A' that you see is a special sequence that means 'not achievable'\n"
+ message += f"student answer: {pred}\n"
+ message += "Conclude the judgement by correct/incorrect/partially correct."
+ messages = [
+ {"role": "system", "content": "You are a helpful assistant"},
+ {"role": "user", "content": message},
+ ]
+
+ response = None
+ if azure_config is None:
+ response = generate_from_openai_chat_completion(
+ model="gpt-4-1106-preview",
+ messages=messages,
+ temperature=0,
+ max_tokens=768,
+ top_p=1.0,
+ context_length=0,
+ ).lower()
+ else:
+ client = autogen.OpenAIWrapper(**azure_config)
+ raw_response = client.create(context=None, messages=messages)
+ response = client.extract_text_or_completion_object(raw_response)[0].lower()
+
+ if "partially correct" in response or "incorrect" in response:
+ return 0.0
+ else:
+ assert "correct" in response
+ return 1.0
+
+
+def llm_ua_match(pred: str, reference: str, question: str, azure_config: dict[str, Any] | None) -> float:
+ """Check whether the prediction matches the reference with GPT-turbo"""
+ messages: list[dict[str, Any]] = []
+ # construct the question to ask
+ message = ""
+ message += f"task: {question}\n"
+ message += f"actual unachievable reason: {reference}\n"
+ message += f"reported unachievable reason: {pred}\n"
+ message += (
+ "The task described above is inherently unachievable due to the reason specified under 'actual unachievable reason'. "
+ "An individual previously attempted this task and was unable to complete it. They provided a reason for their failure, "
+ "which is listed under 'reported unachievable reason'. Your role is to review both the actual and reported reasons. "
+ "Determine if the reported reason aligns with the actual reason, even if implicitly. "
+ "If the stated reason is in line with the actual reason, respond with 'same'. Otherwise, respond with 'different'."
+ )
+ messages = [
+ {"role": "system", "content": "You are a helpful assistant"},
+ {"role": "user", "content": message},
+ ]
+
+ response = None
+ if azure_config is None:
+ response = generate_from_openai_chat_completion(
+ model="gpt-4-1106-preview",
+ messages=messages,
+ temperature=0,
+ max_tokens=768,
+ top_p=1.0,
+ context_length=0,
+ ).lower()
+ else:
+ client = autogen.OpenAIWrapper(**azure_config)
+ raw_response = client.create(context=None, messages=messages)
+ response = client.extract_text_or_completion_object(raw_response)[0].lower()
+
+ if "different" in response:
+ return 0.0
+ else:
+ assert "same" in response
+ return 1.0
+
+
+class PseudoPage:
+ def __init__(self, original_page: Page, url: str):
+ self.url = url
+ self.original_page = original_page
+
+ def __getattr__(self, attr: str) -> Any:
+ # Delegate attribute access to the original page object
+ if attr not in ["url"]:
+ return getattr(self.original_page, attr)
+ else:
+ return getattr(self, attr)
diff --git a/python/benchmarks/WebArena/Templates/Common/evaluation_harness/openai_utils.py b/python/benchmarks/WebArena/Templates/Common/evaluation_harness/openai_utils.py
new file mode 100644
index 000000000..1381f392c
--- /dev/null
+++ b/python/benchmarks/WebArena/Templates/Common/evaluation_harness/openai_utils.py
@@ -0,0 +1,275 @@
+"""Tools to generate from OpenAI prompts.
+Adopted from https://github.com/zeno-ml/zeno-build/"""
+
+import asyncio
+import logging
+import os
+import random
+import time
+from typing import Any
+
+import aiolimiter
+import openai
+from openai import AsyncOpenAI, OpenAI
+
+client = None
+aclient = None
+if "OPENAI_API_KEY" not in os.environ and "OAI_CONFIG_LIST" not in os.environ:
+ raise ValueError("Neither OPENAI_API_KEY nor OAI_CONFIG_LIST is defined in the environment.")
+
+if "OPENAI_API_KEY" in os.environ:
+ client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
+ aclient = AsyncOpenAI(api_key=os.environ["OPENAI_API_KEY"])
+from tqdm.asyncio import tqdm_asyncio
+
+
+def retry_with_exponential_backoff( # type: ignore
+ func,
+ initial_delay: float = 1,
+ exponential_base: float = 2,
+ jitter: bool = True,
+ max_retries: int = 3,
+ errors: tuple[Any] = (
+ openai.RateLimitError,
+ openai.BadRequestError,
+ openai.InternalServerError,
+ ),
+):
+ """Retry a function with exponential backoff."""
+
+ def wrapper(*args, **kwargs): # type: ignore
+ # Initialize variables
+ num_retries = 0
+ delay = initial_delay
+
+ # Loop until a successful response or max_retries is hit or an exception is raised
+ while True:
+ try:
+
+ return func(*args, **kwargs)
+
+ # Retry on specified errors
+ except errors:
+ # Increment retries
+ num_retries += 1
+
+ # Check if max retries has been reached
+ if num_retries > max_retries:
+ raise Exception(f"Maximum number of retries ({max_retries}) exceeded.")
+
+ # Increment the delay
+ delay *= exponential_base * (1 + jitter * random.random())
+
+ # Sleep for the delay
+ time.sleep(delay)
+
+ # Raise exceptions for any errors not specified
+ except Exception as e:
+ raise e
+
+ return wrapper
+
+
+async def _throttled_openai_completion_acreate(
+ engine: str,
+ prompt: str,
+ temperature: float,
+ max_tokens: int,
+ top_p: float,
+ limiter: aiolimiter.AsyncLimiter,
+) -> dict[str, Any]:
+ async with limiter:
+ for _ in range(3):
+ try:
+ return await aclient.completions.create(
+ engine=engine,
+ prompt=prompt,
+ temperature=temperature,
+ max_tokens=max_tokens,
+ top_p=top_p,
+ )
+ except openai.RateLimitError:
+ logging.warning("OpenAI API rate limit exceeded. Sleeping for 10 seconds.")
+ await asyncio.sleep(10)
+ except openai.APIError as e:
+ logging.warning(f"OpenAI API error: {e}")
+ break
+ return {"choices": [{"message": {"content": ""}}]}
+
+
+async def agenerate_from_openai_completion(
+ prompts: list[str],
+ engine: str,
+ temperature: float,
+ max_tokens: int,
+ top_p: float,
+ context_length: int,
+ requests_per_minute: int = 300,
+) -> list[str]:
+ """Generate from OpenAI Completion API.
+
+ Args:
+ prompts: list of prompts
+ temperature: Temperature to use.
+ max_tokens: Maximum number of tokens to generate.
+ top_p: Top p to use.
+ context_length: Length of context to use.
+ requests_per_minute: Number of requests per minute to allow.
+
+ Returns:
+ List of generated responses.
+ """
+ if "OPENAI_API_KEY" not in os.environ:
+ raise ValueError("OPENAI_API_KEY environment variable must be set when using OpenAI API.")
+
+ limiter = aiolimiter.AsyncLimiter(requests_per_minute)
+ async_responses = [
+ _throttled_openai_completion_acreate(
+ engine=engine,
+ prompt=prompt,
+ temperature=temperature,
+ max_tokens=max_tokens,
+ top_p=top_p,
+ limiter=limiter,
+ )
+ for prompt in prompts
+ ]
+ responses = await tqdm_asyncio.gather(*async_responses)
+ return [x["choices"][0]["text"] for x in responses]
+
+
+@retry_with_exponential_backoff
+def generate_from_openai_completion(
+ prompt: str,
+ engine: str,
+ temperature: float,
+ max_tokens: int,
+ top_p: float,
+ context_length: int,
+ stop_token: str | None = None,
+) -> str:
+ if "OPENAI_API_KEY" not in os.environ:
+ raise ValueError("OPENAI_API_KEY environment variable must be set when using OpenAI API.")
+
+ response = client.completions.create(
+ prompt=prompt,
+ engine=engine,
+ temperature=temperature,
+ max_tokens=max_tokens,
+ top_p=top_p,
+ stop=[stop_token],
+ )
+ answer: str = response["choices"][0]["text"]
+ return answer
+
+
+async def _throttled_openai_chat_completion_acreate(
+ model: str,
+ messages: list[dict[str, str]],
+ temperature: float,
+ max_tokens: int,
+ top_p: float,
+ limiter: aiolimiter.AsyncLimiter,
+) -> dict[str, Any]:
+ async with limiter:
+ for _ in range(3):
+ try:
+ return await aclient.chat.completions.create(
+ model=model,
+ messages=messages,
+ temperature=temperature,
+ max_tokens=max_tokens,
+ top_p=top_p,
+ )
+ except openai.RateLimitError:
+ logging.warning("OpenAI API rate limit exceeded. Sleeping for 10 seconds.")
+ await asyncio.sleep(10)
+ except asyncio.exceptions.TimeoutError:
+ logging.warning("OpenAI API timeout. Sleeping for 10 seconds.")
+ await asyncio.sleep(10)
+ except openai.APIError as e:
+ logging.warning(f"OpenAI API error: {e}")
+ break
+ return {"choices": [{"message": {"content": ""}}]}
+
+
+async def agenerate_from_openai_chat_completion(
+ messages_list: list[list[dict[str, str]]],
+ engine: str,
+ temperature: float,
+ max_tokens: int,
+ top_p: float,
+ context_length: int,
+ requests_per_minute: int = 300,
+) -> list[str]:
+ """Generate from OpenAI Chat Completion API.
+
+ Args:
+ messages_list: list of message list
+ temperature: Temperature to use.
+ max_tokens: Maximum number of tokens to generate.
+ top_p: Top p to use.
+ context_length: Length of context to use.
+ requests_per_minute: Number of requests per minute to allow.
+
+ Returns:
+ List of generated responses.
+ """
+ if "OPENAI_API_KEY" not in os.environ:
+ raise ValueError("OPENAI_API_KEY environment variable must be set when using OpenAI API.")
+
+ limiter = aiolimiter.AsyncLimiter(requests_per_minute)
+ async_responses = [
+ _throttled_openai_chat_completion_acreate(
+ model=engine,
+ messages=message,
+ temperature=temperature,
+ max_tokens=max_tokens,
+ top_p=top_p,
+ limiter=limiter,
+ )
+ for message in messages_list
+ ]
+ responses = await tqdm_asyncio.gather(*async_responses)
+ return [x["choices"][0]["message"]["content"] for x in responses]
+
+
+@retry_with_exponential_backoff
+def generate_from_openai_chat_completion(
+ messages: list[dict[str, str]],
+ model: str,
+ temperature: float,
+ max_tokens: int,
+ top_p: float,
+ context_length: int,
+ stop_token: str | None = None,
+) -> str:
+ if "OPENAI_API_KEY" not in os.environ:
+ raise ValueError("OPENAI_API_KEY environment variable must be set when using OpenAI API.")
+ response = client.chat.completions.create(
+ model=model,
+ messages=messages,
+ temperature=temperature,
+ max_tokens=max_tokens,
+ top_p=top_p,
+ )
+ answer: str = response.choices[0].message.content
+ return answer
+
+
+@retry_with_exponential_backoff
+# debug only
+def fake_generate_from_openai_chat_completion(
+ messages: list[dict[str, str]],
+ model: str,
+ temperature: float,
+ max_tokens: int,
+ top_p: float,
+ context_length: int,
+ stop_token: str | None = None,
+) -> str:
+ if "OPENAI_API_KEY" not in os.environ:
+ raise ValueError("OPENAI_API_KEY environment variable must be set when using OpenAI API.")
+
+ answer = "Let's think step-by-step. This page shows a list of links and buttons. There is a search box with the label 'Search query'. I will click on the search box to type the query. So the action I will perform is \"click [60]\"."
+ return answer
diff --git a/python/benchmarks/WebArena/Templates/TeamOne/full_task.json.txt b/python/benchmarks/WebArena/Templates/TeamOne/full_task.json.txt
new file mode 100644
index 000000000..2b53498b8
--- /dev/null
+++ b/python/benchmarks/WebArena/Templates/TeamOne/full_task.json.txt
@@ -0,0 +1 @@
+__FULL_TASK__
diff --git a/python/benchmarks/WebArena/Templates/TeamOne/requirements.txt b/python/benchmarks/WebArena/Templates/TeamOne/requirements.txt
new file mode 100644
index 000000000..6270e241e
--- /dev/null
+++ b/python/benchmarks/WebArena/Templates/TeamOne/requirements.txt
@@ -0,0 +1,2 @@
+/agnext/teams/team-one
+pyautogen
diff --git a/python/benchmarks/WebArena/Templates/TeamOne/scenario.py b/python/benchmarks/WebArena/Templates/TeamOne/scenario.py
new file mode 100644
index 000000000..cc37f8b07
--- /dev/null
+++ b/python/benchmarks/WebArena/Templates/TeamOne/scenario.py
@@ -0,0 +1,260 @@
+import asyncio
+import logging
+import json
+import os
+import re
+import nltk
+
+from typing import Any, Dict, List, Tuple, Union
+from agnext.application import SingleThreadedAgentRuntime
+from agnext.application.logging import EVENT_LOGGER_NAME
+from agnext.components.models import (
+ AzureOpenAIChatCompletionClient,
+ ChatCompletionClient,
+ ModelCapabilities,
+ UserMessage,
+ SystemMessage,
+ LLMMessage,
+)
+from agnext.components.code_executor import LocalCommandLineCodeExecutor
+from agnext.application.logging import EVENT_LOGGER_NAME
+from team_one.markdown_browser import MarkdownConverter, UnsupportedFormatException
+from team_one.agents.coder import Coder, Executor
+from team_one.agents.orchestrator import RoundRobinOrchestrator, LedgerOrchestrator
+from team_one.messages import BroadcastMessage, OrchestrationEvent, RequestReplyMessage, ResetMessage, DeactivateMessage
+from team_one.agents.multimodal_web_surfer import MultimodalWebSurfer
+from team_one.agents.file_surfer import FileSurfer
+from team_one.utils import LogHandler, message_content_to_str, create_completion_client_from_env
+
+
+import evaluation_harness
+from evaluation_harness.env_config import (
+ ACCOUNTS,
+ GITLAB,
+ MAP,
+ REDDIT,
+ SHOPPING,
+ SHOPPING_ADMIN,
+ WIKIPEDIA,
+ HOMEPAGE,
+ SITE_URLS,
+ LOGIN_PROMPTS,
+ SITE_DESCRIPTIONS,
+ url_to_sitename,
+)
+
+REPLACEMENTS = {
+ "__REDDIT__": REDDIT,
+ "__SHOPPING__": SHOPPING,
+ "__SHOPPING_ADMIN__": SHOPPING_ADMIN,
+ "__GITLAB__": GITLAB,
+ "__WIKIPEDIA__": WIKIPEDIA,
+ "__MAP__": MAP,
+ "__HOMEPAGE__": HOMEPAGE,
+}
+
+nltk.download("punkt")
+
+
+async def response_preparer(task: str, source: str, client: ChatCompletionClient, transcript: List[LLMMessage]) -> str:
+ messages: List[LLMMessage] = [
+ UserMessage(
+ content=f"Earlier you were asked the following:\n\n{task}\n\nYour team then worked diligently to address that request. Here is a transcript of that conversation:",
+ source=source,
+ )
+ ]
+
+ # copy them to this context
+ for message in transcript:
+ messages.append(
+ UserMessage(
+ content = message_content_to_str(message.content),
+ # TODO fix this -> remove type ignore
+ source=message.source, # type: ignore
+ )
+ )
+
+ # ask for the final answer
+ messages.append(
+ UserMessage(
+ content= f"""
+Read the above conversation and output a FINAL ANSWER to the original request. The original request is repeated here for convenience:
+
+{task}
+
+To output the final answer, use the following template: FINAL ANSWER: [YOUR FINAL ANSWER]
+Your FINAL ANSWER should be as few words as possible.
+If the original request was not a question, or you did not find a definitive answer, simply summarize the final state of the page or task as your FINAL ANSWER.""",
+ source=source,
+ )
+ )
+
+ response = await client.create(messages)
+ assert isinstance(response.content, str)
+ return response.content
+
+
+async def main() -> None:
+ # Expand the prompt and the full task
+ task_prompt = ""
+ TASK = None
+ with open("task_prompt.json.txt", "rt") as fh:
+ task_prompt = fh.read()
+ with open("task_prompt.json", "wt") as fh:
+ for k in REPLACEMENTS:
+ task_prompt = task_prompt.replace(k, REPLACEMENTS[k])
+ fh.write(task_prompt)
+ TASK = json.loads(task_prompt)
+ if TASK["start_url"] == REDDIT:
+ TASK["start_url"] = TASK["start_url"] + "/forums/all"
+
+ full_task = ""
+ with open("full_task.json.txt", "rt") as fh:
+ full_task = fh.read()
+ with open("full_task.json", "wt") as fh:
+ for k in REPLACEMENTS:
+ full_task = full_task.replace(k, REPLACEMENTS[k])
+ fh.write(full_task)
+
+ # Create the runtime.
+ runtime = SingleThreadedAgentRuntime()
+
+ # Create the AzureOpenAI client, with AAD auth
+ # token_provider = get_bearer_token_provider(DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default")
+ client = AzureOpenAIChatCompletionClient(
+ api_version="2024-02-15-preview",
+ azure_endpoint="https://aif-complex-tasks-west-us-3.openai.azure.com/",
+ model="gpt-4o-2024-05-13",
+ model_capabilities=ModelCapabilities(
+ function_calling=True, json_output=True, vision=True
+ ),
+ # azure_ad_token_provider=token_provider
+ )
+
+ # Login assistant
+ login_assistant = await runtime.register_and_get_proxy(
+ "LoginAssistant",
+ lambda: Coder(
+ model_client=client,
+ system_messages=[
+ SystemMessage("""You are a general-purpose AI assistant and can handle many questions -- but you don't have access to a web browser. However, the user you are talking to does have a browser, and you can see the screen. Provide short direct instructions to them to take you where you need to go to answer the initial question posed to you.
+
+Once the user has taken the final necessary action to complete the task, and you have fully addressed the initial request, reply with the word TERMINATE.""",
+ )
+ ],
+ ),
+ )
+
+ # Web surfer
+ web_surfer = await runtime.register_and_get_proxy(
+ "WebSurfer",
+ lambda: MultimodalWebSurfer(), # Configuration is set later by init()
+ )
+
+ actual_surfer = await runtime.try_get_underlying_agent_instance(web_surfer.id, type=MultimodalWebSurfer)
+ await actual_surfer.init(model_client=client, downloads_folder=os.getcwd(), browser_channel="chromium")
+
+ # Round-robin orchestrator
+ round_robin_orc = await runtime.register_and_get_proxy("round_robin_orc", lambda: RoundRobinOrchestrator(
+ agents=[web_surfer, login_assistant],
+ )
+ )
+
+ # Login to the necessary websites
+ for site in TASK["sites"]:
+ if site in ["reddit", "gitlab", "shopping", "shopping_admin"]:
+ actual_surfer.start_page = SITE_URLS[site]
+
+ run_context = runtime.start()
+ await runtime.publish_message(ResetMessage(), namespace="default")
+ await runtime.publish_message(
+ BroadcastMessage(content=UserMessage(content=LOGIN_PROMPTS[site], source="human")),
+ namespace="default",
+ )
+ await run_context.stop_when_idle()
+
+ # Deactivate the login-related agents
+ run_context = runtime.start()
+ await runtime.send_message(DeactivateMessage(), login_assistant.id)
+ await runtime.send_message(DeactivateMessage(), round_robin_orc.id)
+ await run_context.stop_when_idle()
+
+ # By this point, we should be logged in. Prepare for the main event
+ coder = await runtime.register_and_get_proxy(
+ "Coder",
+ lambda: Coder(model_client=client),
+ )
+
+ executor = await runtime.register_and_get_proxy(
+ "Executor",
+ lambda: Executor(
+ "A agent for executing code", executor=LocalCommandLineCodeExecutor()
+ ),
+ )
+
+ file_surfer = await runtime.register_and_get_proxy(
+ "file_surfer",
+ lambda: FileSurfer(model_client=client),
+ )
+
+ orchestrator = await runtime.register_and_get_proxy("orchestrator", lambda: LedgerOrchestrator(
+ agents=[coder, executor, file_surfer, web_surfer],
+ model_client=client,
+ ))
+
+ # The main event
+ actual_surfer.start_page = TASK["start_url"]
+ run_context = runtime.start()
+ await runtime.send_message(ResetMessage(), web_surfer.id)
+
+ # Provide some background about the pages
+ site_description_prompt = ""
+ sitename = url_to_sitename(TASK["start_url"])
+ if sitename:
+ site_description_prompt = ", " + SITE_DESCRIPTIONS[sitename]
+ task = f"Your web browser is currently open to the website {TASK['start_url']}{site_description_prompt}. On this website, please complete the following task:\n\n{TASK['intent']}"
+
+ await runtime.publish_message(
+ BroadcastMessage(content=UserMessage(content=task.strip(), source="human")),
+ namespace="default",
+ )
+
+ await run_context.stop_when_idle()
+
+ # Output the final answer
+ actual_orchestrator = await runtime.try_get_underlying_agent_instance(orchestrator.id, type=LedgerOrchestrator)
+ transcript: List[LLMMessage] = actual_orchestrator._chat_history # type: ignore
+ final_answer = await response_preparer(task=TASK["intent"], source=(await orchestrator.metadata)["name"], client=client, transcript=transcript)
+
+ m = re.search("FINAL ANSWER:(.*)$", final_answer, re.DOTALL)
+ if m:
+ final_answer = m.group(1).strip()
+
+ print('page.stop("' + final_answer + '")')
+ print("MAIN TASK COMPLETE !#!#")
+
+ ########## EVALUATION ##########
+ context = actual_surfer._context
+ page = actual_surfer._page
+ cdp_session = context.new_cdp_session(page)
+ config_file = "full_task.json"
+
+ evaluator = evaluation_harness.evaluator_router(config_file)
+ score = "N/A"
+ #score = evaluator(
+ # trajectory=evaluation_harness.make_answer_trajecotry(final_answer),
+ # config_file=config_file,
+ # page=page,
+ # client=cdp_session,
+ # azure_config=llm_config,
+ #)
+
+ print("FINAL SCORE: " + str(score))
+
+
+if __name__ == "__main__":
+ logger = logging.getLogger(EVENT_LOGGER_NAME)
+ logger.setLevel(logging.INFO)
+ log_handler = LogHandler()
+ logger.handlers = [log_handler]
+ asyncio.run(main())
diff --git a/python/benchmarks/WebArena/Templates/TeamOne/task_prompt.json.txt b/python/benchmarks/WebArena/Templates/TeamOne/task_prompt.json.txt
new file mode 100644
index 000000000..2ec4f7ee3
--- /dev/null
+++ b/python/benchmarks/WebArena/Templates/TeamOne/task_prompt.json.txt
@@ -0,0 +1 @@
+__TASK_PROMPT__
diff --git a/python/teams/team-one/src/team_one/agents/base_agent.py b/python/teams/team-one/src/team_one/agents/base_agent.py
index 11c359d76..7e9aa475f 100644
--- a/python/teams/team-one/src/team_one/agents/base_agent.py
+++ b/python/teams/team-one/src/team_one/agents/base_agent.py
@@ -1,6 +1,8 @@
+import logging
from asyncio import Lock
from typing import List, Tuple
+from agnext.application.logging import EVENT_LOGGER_NAME
from agnext.components import TypeRoutedAgent, message_handler
from agnext.components.models import (
AssistantMessage,
@@ -9,9 +11,18 @@ from agnext.components.models import (
)
from agnext.core import CancellationToken
-from team_one.messages import BroadcastMessage, RequestReplyMessage, ResetMessage, UserContent
+from team_one.messages import (
+ AgentEvent,
+ BroadcastMessage,
+ DeactivateMessage,
+ RequestReplyMessage,
+ ResetMessage,
+ UserContent,
+)
from team_one.utils import message_content_to_str
+logger = logging.getLogger(EVENT_LOGGER_NAME + ".orchestrator")
+
class BaseAgent(TypeRoutedAgent):
"""An agent that handles the RequestReply and Broadcast messages"""
@@ -24,17 +35,23 @@ class BaseAgent(TypeRoutedAgent):
super().__init__(description)
self._lock: Lock | None = None if handle_messages_concurrently else Lock()
self._chat_history: List[LLMMessage] = []
+ self._enabled: bool = True
@message_handler
async def handle_broadcast(self, message: BroadcastMessage, cancellation_token: CancellationToken) -> None:
"""Handle an incoming broadcast message."""
+ if not self._enabled:
+ return
assert isinstance(message.content, UserMessage)
try:
if self._lock is not None:
await self._lock.acquire()
+ ### CRITICAL SECTION
self._chat_history.append(message.content)
+ ###
+
finally:
if self._lock is not None:
self._lock.release()
@@ -42,11 +59,41 @@ class BaseAgent(TypeRoutedAgent):
@message_handler
async def handle_reset(self, message: ResetMessage, cancellation_token: CancellationToken) -> None:
"""Handle a reset message."""
+ if not self._enabled:
+ return
+
try:
if self._lock is not None:
await self._lock.acquire()
+ ### CRITICAL SECTION
await self._reset(cancellation_token)
+ ###
+
+ finally:
+ if self._lock is not None:
+ self._lock.release()
+
+ @message_handler
+ async def handle_deactivate(self, message: DeactivateMessage, cancellation_token: CancellationToken) -> None:
+ """Handle a deactivate message."""
+ if not self._enabled:
+ return
+
+ try:
+ if self._lock is not None:
+ await self._lock.acquire()
+
+ ### CRITICAL SECTION
+ self._enabled = False
+ logger.info(
+ AgentEvent(
+ f"{self.metadata['name']} (deactivated)",
+ "",
+ )
+ )
+ ###
+
finally:
if self._lock is not None:
self._lock.release()
@@ -54,10 +101,14 @@ class BaseAgent(TypeRoutedAgent):
@message_handler
async def handle_request_reply(self, message: RequestReplyMessage, cancellation_token: CancellationToken) -> None:
"""Respond to a reply request."""
+ if not self._enabled:
+ return
+
try:
if self._lock is not None:
await self._lock.acquire()
+ ### CRITICAL SECTION
request_halt, response = await self._generate_reply(cancellation_token)
assistant_message = AssistantMessage(content=message_content_to_str(response), source=self.metadata["name"])
@@ -65,6 +116,8 @@ class BaseAgent(TypeRoutedAgent):
user_message = UserMessage(content=response, source=self.metadata["name"])
await self.publish_message(BroadcastMessage(content=user_message, request_halt=request_halt))
+ ###
+
finally:
if self._lock is not None:
self._lock.release()
diff --git a/python/teams/team-one/src/team_one/agents/base_orchestrator.py b/python/teams/team-one/src/team_one/agents/base_orchestrator.py
index d8f903386..7532d2616 100644
--- a/python/teams/team-one/src/team_one/agents/base_orchestrator.py
+++ b/python/teams/team-one/src/team_one/agents/base_orchestrator.py
@@ -6,7 +6,7 @@ from agnext.components import TypeRoutedAgent, message_handler
from agnext.components.models import AssistantMessage, LLMMessage, UserMessage
from agnext.core import AgentProxy, CancellationToken
-from ..messages import BroadcastMessage, OrchestrationEvent, RequestReplyMessage
+from ..messages import BroadcastMessage, DeactivateMessage, OrchestrationEvent, RequestReplyMessage
from ..utils import message_content_to_str
logger = logging.getLogger(EVENT_LOGGER_NAME + ".orchestrator")
@@ -23,10 +23,15 @@ class BaseOrchestrator(TypeRoutedAgent):
self._agents = agents
self._max_rounds = max_rounds
self._num_rounds = 0
+ self._enabled = True
@message_handler
async def handle_incoming_message(self, message: BroadcastMessage, cancellation_token: CancellationToken) -> None:
"""Handle an incoming message."""
+
+ if not self._enabled:
+ return
+
source = "Unknown"
if isinstance(message.content, UserMessage) or isinstance(message.content, AssistantMessage):
source = message.content.source
@@ -76,6 +81,19 @@ class BaseOrchestrator(TypeRoutedAgent):
self._num_rounds += 1 # Call before sending the message
await self.send_message(request_reply_message, next_agent.id)
+ @message_handler
+ async def handle_deactivate_message(
+ self, message: DeactivateMessage, cancellation_token: CancellationToken
+ ) -> None:
+ """Handle a deactivate message."""
+ self._enabled = False
+ logger.info(
+ OrchestrationEvent(
+ f"{self.metadata['name']} (deactivated)",
+ "",
+ )
+ )
+
async def _select_next_agent(self, message: LLMMessage) -> Optional[AgentProxy]:
raise NotImplementedError()
diff --git a/python/teams/team-one/src/team_one/agents/multimodal_web_surfer/multimodal_web_surfer.py b/python/teams/team-one/src/team_one/agents/multimodal_web_surfer/multimodal_web_surfer.py
index 5d40180f3..60c6ceac8 100644
--- a/python/teams/team-one/src/team_one/agents/multimodal_web_surfer/multimodal_web_surfer.py
+++ b/python/teams/team-one/src/team_one/agents/multimodal_web_surfer/multimodal_web_surfer.py
@@ -204,7 +204,6 @@ setInterval(function() {{
future = super()._reset(cancellation_token)
await future
await self._visit_page(self.start_page)
- await self._page.wait_for_load_state()
if self.debug_dir:
await self._page.screenshot(path=os.path.join(self.debug_dir, "screenshot.png"))
logger.info(
@@ -609,6 +608,7 @@ When deciding between tools, consider if the request can be best addressed by:
try:
# Regular webpage
await self._page.goto(url)
+ await self._page.wait_for_load_state()
self._prior_metadata_hash = None
except Exception as e_outer:
# Downloaded file
diff --git a/python/teams/team-one/src/team_one/messages.py b/python/teams/team-one/src/team_one/messages.py
index 0623760a2..e50d10aac 100644
--- a/python/teams/team-one/src/team_one/messages.py
+++ b/python/teams/team-one/src/team_one/messages.py
@@ -27,12 +27,23 @@ class ResetMessage:
pass
+@dataclass
+class DeactivateMessage:
+ pass
+
+
@dataclass
class OrchestrationEvent:
source: str
message: str
+@dataclass
+class AgentEvent:
+ source: str
+ message: str
+
+
@dataclass
class WebSurferEvent:
source: str
diff --git a/python/teams/team-one/src/team_one/utils.py b/python/teams/team-one/src/team_one/utils.py
index c86660422..19d0221bc 100644
--- a/python/teams/team-one/src/team_one/utils.py
+++ b/python/teams/team-one/src/team_one/utils.py
@@ -15,6 +15,7 @@ from agnext.components.models import (
)
from .messages import (
+ AgentEvent,
AssistantContent,
FunctionExecutionContent,
OrchestrationEvent,
@@ -107,44 +108,58 @@ class LogHandler(logging.FileHandler):
def emit(self, record: logging.LogRecord) -> None:
# try:
- if True:
- ts = datetime.fromtimestamp(record.created).isoformat()
- if isinstance(record.msg, OrchestrationEvent):
- console_message = (
- f"\n{'-'*75} \n" f"\033[91m[{ts}], {record.msg.source}:\033[0m\n" f"\n{record.msg.message}"
- )
- print(console_message, flush=True)
- record.msg = json.dumps(
- {
- "timestamp": ts,
- "source": record.msg.source,
- "message": record.msg.message,
- "type": "OrchestrationEvent",
- }
- )
- super().emit(record)
- if isinstance(record.msg, WebSurferEvent):
- console_message = f"\033[96m[{ts}], {record.msg.source}: {record.msg.message}\033[0m"
- print(console_message, flush=True)
- payload: Dict[str, Any] = {
+ ts = datetime.fromtimestamp(record.created).isoformat()
+ if isinstance(record.msg, OrchestrationEvent):
+ console_message = (
+ f"\n{'-'*75} \n" f"\033[91m[{ts}], {record.msg.source}:\033[0m\n" f"\n{record.msg.message}"
+ )
+ print(console_message, flush=True)
+ record.msg = json.dumps(
+ {
"timestamp": ts,
- "type": "WebSurferEvent",
+ "source": record.msg.source,
+ "message": record.msg.message,
+ "type": "OrchestrationEvent",
}
- payload.update(asdict(record.msg))
- record.msg = json.dumps(payload)
- super().emit(record)
- if isinstance(record.msg, LLMCallEvent):
- record.msg = json.dumps(
- {
- "timestamp": ts,
- "prompt_tokens": record.msg.prompt_tokens,
- "completion_tokens": record.msg.completion_tokens,
- "type": "LLMCallEvent",
- }
- )
- super().emit(record)
- # except Exception:
- # self.handleError(record)
+ )
+ super().emit(record)
+ elif isinstance(record.msg, AgentEvent):
+ console_message = (
+ f"\n{'-'*75} \n" f"\033[91m[{ts}], {record.msg.source}:\033[0m\n" f"\n{record.msg.message}"
+ )
+ print(console_message, flush=True)
+ record.msg = json.dumps(
+ {
+ "timestamp": ts,
+ "source": record.msg.source,
+ "message": record.msg.message,
+ "type": "AgentEvent",
+ }
+ )
+ super().emit(record)
+ elif isinstance(record.msg, WebSurferEvent):
+ console_message = f"\033[96m[{ts}], {record.msg.source}: {record.msg.message}\033[0m"
+ print(console_message, flush=True)
+ payload: Dict[str, Any] = {
+ "timestamp": ts,
+ "type": "WebSurferEvent",
+ }
+ payload.update(asdict(record.msg))
+ record.msg = json.dumps(payload)
+ super().emit(record)
+ elif isinstance(record.msg, LLMCallEvent):
+ record.msg = json.dumps(
+ {
+ "timestamp": ts,
+ "prompt_tokens": record.msg.prompt_tokens,
+ "completion_tokens": record.msg.completion_tokens,
+ "type": "LLMCallEvent",
+ }
+ )
+ super().emit(record)
+
+ # except Exception:
+ # self.handleError(record)
class SentinelMeta(type):