Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

Dataset selector in Dataset Explorer (#50)

Dmitrii Khizbullin98f87be81146
diff --git a/apps/data_explorer/data_explorer.py b/apps/data_explorer/data_explorer.py
index 1a77284a8..046e575c5 100644
--- a/apps/data_explorer/data_explorer.py
+++ b/apps/data_explorer/data_explorer.py
@@ -4,18 +4,21 @@ Gradio-based web UI to explore the Camel dataset.
import argparse
import random
-from typing import Any, Dict, List, Tuple
+from typing import Dict, List, Tuple
import gradio as gr
-from loader import load_data
+from loader import Datasets, load_datasets
def parse_arguments():
""" Get command line arguments. """
parser = argparse.ArgumentParser("Camel data explorer")
- parser.add_argument('--data-path', type=str, default="camel_data/",
- help='Path to the folder with chat JSONs')
+ parser.add_argument(
+ '--data-path', type=str, default=None,
+ help='Path to the folder with ZIP datasets containing JSONs')
+ parser.add_argument('--default-dataset', type=str, default=None,
+ help='Default dataset name selected from ZIPs')
parser.add_argument('--share', type=bool, default=False,
help='Expose the web UI to Gradio')
parser.add_argument('--server-port', type=int, default=8080,
@@ -32,39 +35,144 @@ def parse_arguments():
return args
-def construct_demo(data: Dict[str, Any]):
+def construct_app(datasets: Datasets, default_dataset: str = None):
""" Build Gradio UI and populate with chat data from JSONs.
Args:
- data (Dict[str, Any]): Parsed multi-JSON dataset with chats.
+ datasets (Datasets): Several parsed
+ multi-JSON dataset with chats.
+ default_dataset (str): Default selection of the dataset.
Returns:
None
"""
- assistant_roles = data['assistant_roles']
- user_roles = data['user_roles']
- assistant_role = random.choice(assistant_roles) \
- if len(assistant_roles) > 0 else ""
- user_role = random.choice(user_roles) if len(user_roles) > 0 else ""
+
+ if default_dataset is None:
+ default_dataset = "ai_society_chat"
+
+ misalignment_set_names = {"misalignment"}
+ ordinary_datasets = [
+ v for v in datasets.keys() if v not in misalignment_set_names
+ ]
+ misalignment_datasets = [
+ v for v in datasets.keys() if v in misalignment_set_names
+ ]
+ default_dataset_name = default_dataset \
+ if default_dataset in datasets.keys() \
+ else ordinary_datasets[0] if len(ordinary_datasets) > 0 \
+ else misalignment_datasets[0] if len(misalignment_datasets) > 0 \
+ else ""
+ dataset_names = list(datasets.keys())
+
with gr.Row().style():
- with gr.Column(scale=3):
- assistant_dd = gr.Dropdown(assistant_roles, label="ASSISTANT",
- value=assistant_role, interactive=True)
- with gr.Column(scale=3):
- user_dd = gr.Dropdown(user_roles, label="USER", value=user_role,
- interactive=True)
- with gr.Column(scale=3):
+ with gr.Column(scale=2):
+ with gr.Row():
+ dataset_dd = gr.Dropdown(dataset_names, label="Select dataset",
+ value="NODEFAULT", interactive=True)
+ with gr.Row():
+ disclaimer_ta = gr.Markdown(
+ "## By clicking AGREE I consent to use the dataset "
+ "for purely educational and academic purposes and "
+ "not use it for any fraudulent activity; and I take "
+ "all the responsibility if the data is used in a "
+ "malicious application.", visible=False)
+ with gr.Row():
+ with gr.Column(scale=1):
+ accept_disclaimer_bn = gr.Button("AGREE", visible=False)
+ with gr.Column(scale=1):
+ decline_disclaimer_bn = gr.Button("DECLINE", visible=False)
+ with gr.Row():
+ with gr.Column(scale=3):
+ assistant_dd = gr.Dropdown([], label="ASSISTANT", value="",
+ interactive=True)
+ with gr.Column(scale=3):
+ user_dd = gr.Dropdown([], label="USER", value="",
+ interactive=True)
+ with gr.Column(scale=1):
gr.Markdown(
"## CAMEL: Communicative Agents for \"Mind\" Exploration"
" of Large Scale Language Model Society\n"
"Github repo: [https://github.com/lightaime/camel]"
"(https://github.com/lightaime/camel)")
+
task_dd = gr.Dropdown([], label="Original task", value="",
interactive=True)
specified_task_ta = gr.TextArea(label="Specified task", lines=2)
chatbot = gr.Chatbot()
+ accepted_st = gr.State(False)
+
+ def set_default_dataset() -> Dict:
+ """ Trigger for app load.
+
+ Returns:
+ Dict: Update dict for dataset_dd.
+ """
+ return gr.update(value=default_dataset_name)
- def roles_dd_change(assistant_role: str, user_role: str) -> Dict:
+ def check_if_misalignment(dataset_name: str, accepted: bool) \
+ -> Tuple[Dict, Dict, Dict]:
+ """ Display AGREE/DECLINE if needed.
+
+ Returns:
+ Tuple: Visibility updates for the buttons.
+ """
+
+ if dataset_name == "misalignment" and not accepted:
+ return gr.update(visible=True), \
+ gr.update(visible=True), gr.update(visible=True)
+ else:
+ return gr.update(visible=False), \
+ gr.update(visible=False), gr.update(visible=False)
+
+ def enable_misalignment() -> Tuple[bool, Dict, Dict, Dict]:
+ """ Update the state of the accepted disclaimer.
+
+ Returns:
+ Tuple: New state and visibility updates for the buttons.
+ """
+
+ return True, gr.update(visible=False), \
+ gr.update(visible=False), gr.update(visible=False)
+
+ def disable_misalignment() -> Tuple[bool, Dict, Dict, Dict]:
+ """ Update the state of the accepted disclaimer.
+
+ Returns:
+ Tuple: New state and visibility updates for the buttons.
+ """
+
+ return False, gr.update(visible=False), \
+ gr.update(visible=False), gr.update(visible=False)
+
+ def update_dataset_selection(dataset_name: str,
+ accepted: bool) -> Tuple[Dict, Dict]:
+ """ Update roles based on the selected dataset.
+
+ Args:
+ dataset_name (str): Name of the loaded .zip dataset.
+ accepted (bool): If the disclaimer thas been accepted.
+
+ Returns:
+ Tuple[Dict, Dict]: New Assistant and User roles.
+ """
+
+ if dataset_name == "misalignment" and not accepted:
+ # If used did not accept the misalignment policy,
+ # keep the old selection.
+ return (gr.update(value="N/A",
+ choices=[]), gr.update(value="N/A", choices=[]))
+
+ dataset = datasets[dataset_name]
+ assistant_roles = dataset['assistant_roles']
+ user_roles = dataset['user_roles']
+ assistant_role = random.choice(assistant_roles) \
+ if len(assistant_roles) > 0 else ""
+ user_role = random.choice(user_roles) if len(user_roles) > 0 else ""
+ return (gr.update(value=assistant_role, choices=assistant_roles),
+ gr.update(value=user_role, choices=user_roles))
+
+ def roles_dd_change(dataset_name: str, assistant_role: str,
+ user_role: str) -> Dict:
""" Update the displayed chat upon inputs change.
Args:
@@ -74,7 +182,7 @@ def construct_demo(data: Dict[str, Any]):
Returns:
Dict: New original roles state dictionary.
"""
- matrix = data['matrix']
+ matrix = datasets[dataset_name]['matrix']
if (assistant_role, user_role) in matrix:
record: Dict[str, Dict] = matrix[(assistant_role, user_role)]
original_task_options = list(record.keys())
@@ -115,7 +223,7 @@ def construct_demo(data: Dict[str, Any]):
pass
return history
- def task_dd_change(assistant_role: str, user_role: str,
+ def task_dd_change(dataset_name: str, assistant_role: str, user_role: str,
original_task: str) -> Tuple[str, List]:
""" Load task details and chatbot history into UI elements.
@@ -129,7 +237,7 @@ def construct_demo(data: Dict[str, Any]):
and chatbot history UI elements.
"""
- matrix = data['matrix']
+ matrix = datasets[dataset_name]['matrix']
if (assistant_role, user_role) in matrix:
task_dict: Dict[str, Dict] = matrix[(assistant_role, user_role)]
if original_task in task_dict:
@@ -144,22 +252,36 @@ def construct_demo(data: Dict[str, Any]):
history = []
return specified_task, history
- func_args = (roles_dd_change, [assistant_dd, user_dd], task_dd)
+ dataset_dd.change(check_if_misalignment, [dataset_dd, accepted_st],
+ [disclaimer_ta, accept_disclaimer_bn,
+ decline_disclaimer_bn]) \
+ .then(update_dataset_selection,
+ [dataset_dd, accepted_st],
+ [assistant_dd, user_dd])
+
+ accept_disclaimer_bn.click(enable_misalignment, None, [
+ accepted_st, disclaimer_ta, accept_disclaimer_bn, decline_disclaimer_bn
+ ]) \
+ .then(update_dataset_selection,
+ [dataset_dd, accepted_st],
+ [assistant_dd, user_dd])
+
+ decline_disclaimer_bn.click(disable_misalignment, None, [
+ accepted_st, disclaimer_ta, accept_disclaimer_bn, decline_disclaimer_bn
+ ]) \
+ .then(update_dataset_selection,
+ [dataset_dd, accepted_st],
+ [assistant_dd, user_dd])
+
+ func_args = (roles_dd_change, [dataset_dd, assistant_dd, user_dd], task_dd)
assistant_dd.change(*func_args)
user_dd.change(*func_args)
- task_dd.change(task_dd_change, [assistant_dd, user_dd, task_dd],
+ task_dd.change(task_dd_change,
+ [dataset_dd, assistant_dd, user_dd, task_dd],
[specified_task_ta, chatbot])
- task_dd_update_dict = roles_dd_change(assistant_dd.value, user_dd.value)
- task_dd.choices = task_dd_update_dict['choices']
- task_dd.value = task_dd_update_dict['value']
-
- specified_task, chatbot_history = task_dd_change(assistant_dd.value,
- user_dd.value,
- task_dd.value)
- specified_task_ta.value = specified_task
- chatbot.value = chatbot_history
+ demo.load(set_default_dataset, None, dataset_dd)
if __name__ == "__main__":
@@ -168,13 +290,13 @@ if __name__ == "__main__":
args = parse_arguments()
print("Loading the dataset...")
- data = load_data(args.data_path)
+ datasets = load_datasets(args.data_path)
print("Dataset is loaded")
print("Getting Data Explorer web server online...")
with gr.Blocks() as demo:
- construct_demo(data)
+ construct_app(datasets, args.default_dataset)
demo.queue(args.concurrency_count)
demo.launch(share=args.share, inbrowser=args.inbrowser,
diff --git a/apps/data_explorer/loader.py b/apps/data_explorer/loader.py
index 8ff7a0f6d..8fe1932d7 100644
--- a/apps/data_explorer/loader.py
+++ b/apps/data_explorer/loader.py
@@ -6,13 +6,42 @@ import glob
import json
import os
import re
-from typing import Any, Dict, List, Tuple, Union
+import zipfile
+from typing import Any, Dict, List, Optional, Tuple, Union
from tqdm import tqdm
ChatHistory = Dict[str, Any]
ParsedChatHistory = Dict[str, Any]
AllChats = Dict[str, Any]
+Datasets = Dict[str, AllChats]
+
+REPO_ROOT = os.path.realpath(
+ os.path.join(os.path.dirname(os.path.abspath(__file__)), "../.."))
+
+
+class AutoZip:
+ def __init__(self, zip_path: str, ext: str = ".json"):
+ self.zip_path = zip_path
+ self.zip = zipfile.ZipFile(zip_path, "r")
+ self.fl = [f for f in self.zip.filelist if f.filename.endswith(ext)]
+
+ def __next__(self):
+ if self.index >= len(self.fl):
+ raise StopIteration
+ else:
+ finfo = self.fl[self.index]
+ with self.zip.open(finfo) as f:
+ raw_json = json.loads(f.read().decode("utf-8"))
+ self.index += 1
+ return raw_json
+
+ def __len__(self):
+ return len(self.fl)
+
+ def __iter__(self):
+ self.index = 0
+ return self
def parse(raw_chat: ChatHistory) -> Union[ParsedChatHistory, None]:
@@ -74,31 +103,24 @@ def parse(raw_chat: ChatHistory) -> Union[ParsedChatHistory, None]:
)
-def load_data(path: str) -> AllChats:
- """ Load all JSONs from a folder and parse them.
+def load_zip(zip_path: str) -> AllChats:
+ """ Load all JSONs from a zip file and parse them.
Args:
- path (str): path to the folder with JSONs.
+ path (str): path to the ZIP file.
Returns:
AllChats: A dictionary with all possible assistant and
user roles and the matrix of chats.
"""
- filt = os.path.join(path, "*.json")
- files = glob.glob(filt)
+ zip_inst = AutoZip(zip_path)
parsed_list = []
- for file_name in tqdm(files):
- with open(file_name, "rb") as f:
- try:
- raw_chat = json.load(f)
- except Exception as ex:
- print(str(ex))
- continue
- parsed = parse(raw_chat)
- if parsed is None:
- continue
- parsed_list.append(parsed)
+ for raw_chat in tqdm(iter(zip_inst)):
+ parsed = parse(raw_chat)
+ if parsed is None:
+ continue
+ parsed_list.append(parsed)
assistant_roles = set()
user_roles = set()
@@ -128,5 +150,27 @@ def load_data(path: str) -> AllChats:
)
+def load_datasets(path: Optional[str] = None) -> Datasets:
+ """ Load all JSONs from a set of zip files and parse them.
+
+ Args:
+ path (str): path to the folder with ZIP datasets.
+
+ Returns:
+ Datasets: A dictionary of dataset name and dataset contents.
+ """
+
+ if path is None:
+ path = os.path.join(REPO_ROOT, "datasets")
+
+ filt = os.path.join(path, "*.zip")
+ files = glob.glob(filt)
+ datasets = {}
+ for file_name in tqdm(files):
+ name = os.path.splitext(os.path.basename(file_name))[0]
+ datasets[name] = load_zip(file_name)
+ return datasets
+
+
if __name__ == "__main__":
- data = load_data("DATA/")
+ data = load_datasets()