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

Add solution extraction (#115)

Hasan Abed Al Kader Hammoudb8e5f782668b
diff --git a/camel/prompts/__init__.py b/camel/prompts/__init__.py
index 6dc72dec6..c195533a0 100644
--- a/camel/prompts/__init__.py
+++ b/camel/prompts/__init__.py
@@ -3,6 +3,7 @@ from .ai_society import AISocietyPromptTemplateDict
from .code import CodePromptTemplateDict
from .misalignment import MisalignmentPromptTemplateDict
from .translation import TranslationPromptTemplateDict
+from .solution_extraction import SolutionExtractionPromptTemplateDict
from .evaluation import EvaluationPromptTemplateDict
from .task_prompt_template import TaskPromptTemplateDict
from .prompt_templates import PromptTemplateGenerator
@@ -17,4 +18,5 @@ __all__ = [
'EvaluationPromptTemplateDict',
'TaskPromptTemplateDict',
'PromptTemplateGenerator',
+ 'SolutionExtractionPromptTemplateDict',
]
diff --git a/camel/prompts/solution_extraction.py b/camel/prompts/solution_extraction.py
new file mode 100644
index 000000000..c85d3d3f4
--- /dev/null
+++ b/camel/prompts/solution_extraction.py
@@ -0,0 +1,31 @@
+from typing import Any
+
+from camel.prompts import TextPrompt, TextPromptDict
+from camel.typing import RoleType
+
+
+# flake8: noqa
+class SolutionExtractionPromptTemplateDict(TextPromptDict):
+ r"""A dictionary containing :obj:`TextPrompt` used in the `SolutionExtraction`
+ task.
+
+ Attributes:
+ ASSISTANT_PROMPT (TextPrompt): A system prompt for the AI assistant
+ that outlines the rules of the conversation and provides
+ instructions for completing tasks.
+ """
+ ASSISTANT_PROMPT = TextPrompt(
+ """You are an experienced solution extracting agent.
+Your task is to extract full and complete solutions by looking at the conversation between a user and an assistant with particular specializations.
+You should present me with a final and detailed solution purely based on the conversation.
+You should present the solution as if its yours.
+Use present tense and as if you are the one presenting the solution.
+You should not miss any necessary details or examples.
+Keep all provided explanations and codes provided throughout the conversation.
+Remember your task is not to summarize rather to extract the full solution.""")
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ super().__init__(*args, **kwargs)
+ self.update({
+ RoleType.ASSISTANT: self.ASSISTANT_PROMPT,
+ })
diff --git a/camel/prompts/task_prompt_template.py b/camel/prompts/task_prompt_template.py
index 9cdd30446..c54091e76 100644
--- a/camel/prompts/task_prompt_template.py
+++ b/camel/prompts/task_prompt_template.py
@@ -5,6 +5,7 @@ from camel.prompts import (
CodePromptTemplateDict,
EvaluationPromptTemplateDict,
MisalignmentPromptTemplateDict,
+ SolutionExtractionPromptTemplateDict,
TextPromptDict,
TranslationPromptTemplateDict,
)
@@ -24,9 +25,16 @@ class TaskPromptTemplateDict(Dict[Any, TextPromptDict]):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.update({
- TaskType.AI_SOCIETY: AISocietyPromptTemplateDict(),
- TaskType.CODE: CodePromptTemplateDict(),
- TaskType.MISALIGNMENT: MisalignmentPromptTemplateDict(),
- TaskType.TRANSLATION: TranslationPromptTemplateDict(),
- TaskType.EVALUATION: EvaluationPromptTemplateDict(),
+ TaskType.AI_SOCIETY:
+ AISocietyPromptTemplateDict(),
+ TaskType.CODE:
+ CodePromptTemplateDict(),
+ TaskType.MISALIGNMENT:
+ MisalignmentPromptTemplateDict(),
+ TaskType.TRANSLATION:
+ TranslationPromptTemplateDict(),
+ TaskType.EVALUATION:
+ EvaluationPromptTemplateDict(),
+ TaskType.SOLUTION_EXTRACTION:
+ SolutionExtractionPromptTemplateDict(),
})
diff --git a/camel/typing.py b/camel/typing.py
index 7dc1b0a35..99d64978c 100644
--- a/camel/typing.py
+++ b/camel/typing.py
@@ -20,6 +20,7 @@ class TaskType(Enum):
MISALIGNMENT = "misalignment"
TRANSLATION = "translation"
EVALUATION = "evaluation"
+ SOLUTION_EXTRACTION = "solution_extraction"
DEFAULT = "default"
diff --git a/examples/ai_society/role_playing_multiprocess.py b/examples/ai_society/role_playing_multiprocess.py
index b04d69ab3..605759c7c 100644
--- a/examples/ai_society/role_playing_multiprocess.py
+++ b/examples/ai_society/role_playing_multiprocess.py
@@ -1,6 +1,7 @@
import json
import multiprocessing
import os
+import sys
from colorama import Fore
@@ -155,6 +156,13 @@ def generate_data(assistant_idx: int, assistant_role_name: str, user_idx: int,
json.dump(message_dict, json_file)
+def generate_data_wrapper(args):
+ try:
+ generate_data(*args)
+ except Exception as e:
+ print(f"Error in generate_data: {e}", file=sys.stderr)
+
+
def main() -> None:
# Disable/Enable Printing
@@ -184,7 +192,7 @@ def main() -> None:
roles_per_chunk:(array_idx + 1) *
roles_per_chunk]
- pool = multiprocessing.Pool(processes=16)
+ pool = multiprocessing.Pool()
for assistant_idx, assistant_role_name in enumerate(assistant_roles):
assistant_idx += array_idx * roles_per_chunk
@@ -211,9 +219,9 @@ def main() -> None:
f"{(user_idx+1):03}_{(task_idx+1):03}")
if not os.path.exists(f"./camel_data/ai_society/{id}.json"):
pool.apply_async(
- generate_data,
- (assistant_idx, assistant_role_name, user_idx,
- user_role_name, task_idx, task_prompt, verbose))
+ generate_data_wrapper,
+ ((assistant_idx, assistant_role_name, user_idx,
+ user_role_name, task_idx, task_prompt, verbose), ))
pool.close()
pool.join()
diff --git a/examples/summarization/gpt_solution_extraction.py b/examples/summarization/gpt_solution_extraction.py
new file mode 100644
index 000000000..13ea3fac9
--- /dev/null
+++ b/examples/summarization/gpt_solution_extraction.py
@@ -0,0 +1,185 @@
+import concurrent.futures
+import itertools
+import json
+import os
+import random
+from typing import Dict
+
+import numpy as np
+
+from camel.agents import ChatAgent
+from camel.messages import AssistantSystemMessage, UserChatMessage
+from camel.prompts import SolutionExtractionPromptTemplateDict
+from camel.typing import ModelType, RoleType
+
+
+def flatten_conversation(conversation: Dict) -> str:
+ r"""Format a conversation into a string.
+
+ Args:
+ conversation (Dict): A dictionary containing
+ information about the conversation.
+
+ Returns:
+ str: A string containing the specified task and
+ all messages in the conversation.
+
+ Raises:
+ ValueError: If an unknown role name is encountered
+ in the conversation.
+
+ The conversation is formatted in the following format:
+ Task: <specified_task>
+ User (<role_1>): <message_1>
+ Assistant (<role_2>): <message_2>
+ ...
+
+ Example:
+ >>> conversation = {
+ ... 'num_messages': 2,
+ ... 'message_1': {'role_name': 'Engineer', 'content': 'Hello'},
+ ... 'message_2': {'role_name': 'Programmer',
+ 'content': 'Hi there!'},
+
+ ... 'specified_task': 'Answer a greeting'
+ ... }
+ >>> flatten_conversation(conversation)
+ 'Task: Answer a greeting
+ User (Engineer): Hello
+ Assistant (Programmer): Hi there!'
+
+ """
+
+ num_messages = conversation['num_messages']
+ role_1 = conversation['message_1']['role_name']
+ role_2 = conversation['message_2']['role_name']
+ task = conversation['specified_task']
+
+ messages = []
+ for i in range(1, num_messages + 1):
+ if conversation[f'message_{i}']['role_name'] == role_1:
+ message = f"User ({role_1}): " + conversation[f'message_{i}'][
+ 'content']
+ elif conversation[f'message_{i}']['role_name'] == role_2:
+ message = f"Assistant ({role_2}): " + conversation[f'message_{i}'][
+ 'content']
+ else:
+ raise ValueError("Unknown role name: "
+ f"{conversation[f'message_{i}']['role_name']}")
+ messages.append(message)
+
+ joined_messages = '\n'.join(messages)
+ formatted_data = f"Task: {task}\n{joined_messages}"
+
+ return formatted_data
+
+
+def format_combination(combination):
+ assistant_role, user_role, task = combination
+ assistant_role = str(assistant_role).zfill(3)
+ user_role = str(user_role).zfill(3)
+ task = str(task).zfill(3)
+ return f"{assistant_role}_{user_role}_{task}"
+
+
+def solution_extraction(conversation: Dict, flattened_conversation: str,
+ file_name: str) -> None:
+
+ solution_extraction_template = SolutionExtractionPromptTemplateDict()
+ assistant_sys_msg_prompt = solution_extraction_template[RoleType.ASSISTANT]
+
+ assistant_sys_msg = AssistantSystemMessage(
+ role_name="Solution Extractor", content=assistant_sys_msg_prompt)
+
+ # We use GPT4 because it has a longer context length
+ agent = ChatAgent(assistant_sys_msg, model=ModelType.GPT_4)
+ agent.reset()
+
+ prompt = "Here is the conversation:" + flattened_conversation
+
+ user_msg = UserChatMessage(role_name="User", content=prompt)
+ assistant_msg, _, _ = agent.step(user_msg)
+ print(assistant_msg[0].content)
+
+ # Create folder to write solution_extraction to
+ if not os.path.exists(
+ "../camel/camel_data/ai_society_solution_extraction"):
+ os.makedirs("../camel/camel_data/ai_society_solution_extraction")
+
+ # Append to the original JSON conversation file
+ conversation['solution_extraction'] = assistant_msg[0].content
+
+ # Save new dictionary as JSON file
+ with open(f"./camel_data/ai_society_solution_extraction/{file_name}.json",
+ "w") as f:
+ json.dump(conversation, f)
+
+
+def main():
+
+ # Seed for reproducibility
+ np.random.seed(10)
+ random.seed(10)
+
+ total_num_assistant_roles = 50
+ total_num_user_roles = 50
+ total_num_tasks = 1
+
+ subsample_num_assistant_roles = 10
+ subsample_num_user_roles = 10
+ subsample_num_tasks = 1
+
+ # Randomly subsample `subsample_num_assistant_roles`
+ # of the total assistant roles
+ subsampled_assistant_roles = random.sample(
+ range(1, total_num_assistant_roles + 1), subsample_num_assistant_roles)
+
+ # Randomly subsample `subsample_num_user_roles` of the total user roles
+ subsampled_user_roles = random.sample(range(1, total_num_user_roles + 1),
+ subsample_num_user_roles)
+
+ # Randomly subsample `subsample_num_tasks` of the total tasks
+ subsampled_tasks = random.sample(range(1, total_num_tasks + 1),
+ subsample_num_tasks)
+
+ file_names = list(
+ itertools.product(subsampled_assistant_roles, subsampled_user_roles,
+ subsampled_tasks))
+
+ # Formatting is needed to match the names of the original
+ # generated JSON files xxx_xxx_xxx.json
+ file_names = [
+ format_combination(combination) for combination in file_names
+ ]
+
+ # Directory containing original json files
+ # we want to extract solutions from AI Society dataset
+ json_dir = "../camel/camel_data/ai_society/"
+
+ # Check that all files exist
+ for file_name in file_names:
+ json_file = os.path.join(json_dir, file_name + ".json")
+ if not os.path.exists(json_file):
+ raise ValueError(f"File {json_file} does not exist.")
+
+ # Read in json files and extract solutions
+ with concurrent.futures.ProcessPoolExecutor(max_workers=16) as executor:
+ futures = []
+ for file_name in file_names:
+ json_file = os.path.join(json_dir, file_name + ".json")
+ with open(json_file) as f:
+ conversation = json.load(f)
+ flattened_conversation = flatten_conversation(conversation)
+ futures.append(
+ executor.submit(solution_extraction, conversation,
+ flattened_conversation, file_name))
+
+ for future in concurrent.futures.as_completed(futures):
+ try:
+ future.result()
+ except Exception as e:
+ print(f"Exception: {e}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/summarization/gpt_solver.py b/examples/summarization/gpt_solver.py
new file mode 100644
index 000000000..e43068389
--- /dev/null
+++ b/examples/summarization/gpt_solver.py
@@ -0,0 +1,68 @@
+import concurrent.futures
+import json
+import os
+from typing import Dict
+
+from camel.agents import ChatAgent
+from camel.messages import AssistantSystemMessage, UserChatMessage
+
+# Directory containing your json files of CAMEL conversations
+# This code will append a new key called "gpt_solution" to each json file
+# Containing GPT solution to the specified task in the json file
+
+# dir_files = "./camel_data/ai_society_solution_extraction_plus_gpt_solution"
+data_dir = "./camel_data/ai_society_solution_extraction"
+save_dir = "./camel_data/ai_society_solution_extraction_save"
+
+
+def process_file(data: Dict[str, str]) -> None:
+ print(data["id"])
+ assistant_sys_msg = AssistantSystemMessage(
+ role_name="Assistant",
+ content="You are a helpful assistant.",
+ )
+ agent = ChatAgent(assistant_sys_msg)
+ agent.reset()
+
+ prompt = "Solve the following task:\n" + data["specified_task"]
+ user_msg = UserChatMessage(role_name="User", content=prompt)
+ assistant_msg, _, _ = agent.step(user_msg)
+ print(assistant_msg[0].content)
+
+ # Append solution to JSON file as "gpt_solution"
+ data["gpt_solution"] = assistant_msg[0].content
+
+ # create save_dir if not exists
+ if not os.path.exists(save_dir):
+ os.makedirs(save_dir)
+
+ # save result as json file
+ with open(os.path.join(save_dir, data["id"] + ".json"), 'w') as f:
+ json.dump(data, f)
+
+
+def main():
+ # read all json files in data_dir
+ files = [f for f in os.listdir(data_dir) if f.endswith('.json')]
+
+ # load all json files as data list
+ data_list = []
+ for file in files:
+ with open(os.path.join(data_dir, file)) as f:
+ data_list.append(json.load(f))
+
+ # Specify number of processes with max_workers argument (default: 16)
+ with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
+ futures = []
+ for data in data_list:
+ futures.append(executor.submit(process_file, data))
+
+ for future in concurrent.futures.as_completed(futures):
+ try:
+ future.result()
+ except Exception as e:
+ print(f"Exception occurred: {e}")
+
+
+if __name__ == "__main__":
+ main()