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

Fixed Typing Issues (#109)

Hasan Abed Al Kader Hammoud0bdb33ad822a
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.py
index d490b1511..55a95778f 100644
--- a/camel/agents/chat_agent.py
+++ b/camel/agents/chat_agent.py
@@ -88,7 +88,7 @@ class ChatAgent:
"""
self.stored_messages: List[MessageType] = [self.system_message]
- def update_messages(self, message: ChatMessage) -> List[ChatMessage]:
+ def update_messages(self, message: ChatMessage) -> List[MessageType]:
r"""Updates the stored messages list with a new message.
Args:
diff --git a/camel/agents/role_playing.py b/camel/agents/role_playing.py
index 512f5584a..358ccec5b 100644
--- a/camel/agents/role_playing.py
+++ b/camel/agents/role_playing.py
@@ -53,7 +53,7 @@ class RolePlaying:
with_task_planner: bool = False,
with_human_in_the_loop: bool = False,
mode_type: ModelType = ModelType.GPT_3_5_TURBO,
- task_type: Optional[TaskType] = TaskType.AI_SOCIETY,
+ task_type: TaskType = TaskType.AI_SOCIETY,
assistant_agent_kwargs: Optional[Dict] = None,
user_agent_kwargs: Optional[Dict] = None,
task_specify_agent_kwargs: Optional[Dict] = None,
@@ -168,7 +168,10 @@ class RolePlaying:
user_msg = UserChatMessage(role_name=self.user_sys_msg.role_name,
content=f"{self.assistant_sys_msg.content}")
- msgs, _, _ = self.assistant_agent.step(user_msg)
+ msgs, terminated, info = self.assistant_agent.step(user_msg)
+ if terminated or msgs is None:
+ raise ValueError(
+ f"Assistant agent terminated unexpectedly. Error info: {info}")
return assistant_msg, msgs
@@ -192,7 +195,7 @@ class RolePlaying:
if len(messages) > 1 and not self.with_human_in_the_loop:
raise ValueError("Got than one message to process. "
f"Num of messages: {len(messages)}.")
- elif self.with_human_in_the_loop:
+ elif self.with_human_in_the_loop and self.human is not None:
processed_msg = self.human.step(messages)
else:
processed_msg = messages[0]
@@ -227,7 +230,7 @@ class RolePlaying:
"""
user_msgs, user_terminated, user_info = self.user_agent.step(
assistant_msg.to_user_chat_message())
- if user_terminated:
+ if user_terminated or user_msgs is None:
return ((None, None, None), (None, user_terminated, user_info))
user_msg = self.process_messages(user_msgs)
self.user_agent.update_messages(user_msg)
@@ -235,7 +238,7 @@ class RolePlaying:
(assistant_msgs, assistant_terminated,
assistant_info) = self.assistant_agent.step(
user_msg.to_user_chat_message())
- if assistant_terminated:
+ if assistant_terminated or assistant_msgs is None:
return ((None, assistant_terminated, assistant_info),
(user_msg, user_terminated, user_info))
assistant_msg = self.process_messages(assistant_msgs)
diff --git a/camel/agents/task_agent.py b/camel/agents/task_agent.py
index c016c0868..ecce76f2f 100644
--- a/camel/agents/task_agent.py
+++ b/camel/agents/task_agent.py
@@ -143,9 +143,11 @@ class TaskPlannerAgent(ChatAgent):
task_msg = UserChatMessage(role_name="Task Planner",
content=self.task_planner_prompt)
sub_tasks_msgs, terminated, _ = super().step(task_msg)
- sub_tasks_msg = sub_tasks_msgs[0]
+ if sub_tasks_msgs is None:
+ raise RuntimeError("Got None Subtasks messages.")
if terminated:
raise RuntimeError("Task planning failed.")
- else:
- return TextPrompt(sub_tasks_msg.content)
+
+ sub_tasks_msg = sub_tasks_msgs[0]
+ return TextPrompt(sub_tasks_msg.content)
diff --git a/camel/generators.py b/camel/generators.py
index 19bc5af1c..45d8ba562 100644
--- a/camel/generators.py
+++ b/camel/generators.py
@@ -9,7 +9,7 @@ class SystemMessageGenerator:
r"""System message generator for agents.
Args:
- task_type (Optional[TaskType], optional): The task type.
+ task_type (TaskType, optional): The task type.
(default: :obj:`TaskType.AI_SOCIETY`)
sys_prompts (Optional[Dict[RoleType, str]], optional): The prompts of
the system messages for each role type. (default: :obj:`None`)
@@ -20,7 +20,7 @@ class SystemMessageGenerator:
def __init__(
self,
- task_type: Optional[TaskType] = TaskType.AI_SOCIETY,
+ task_type: TaskType = TaskType.AI_SOCIETY,
sys_prompts: Optional[Dict[RoleType, str]] = None,
sys_msg_meta_dict_keys: Optional[Set[str]] = None,
) -> None:
diff --git a/camel/messages.py b/camel/messages.py
index 885a559aa..d5e8355a8 100644
--- a/camel/messages.py
+++ b/camel/messages.py
@@ -233,7 +233,7 @@ class AssistantChatMessage(ChatMessage):
"""
role_name: str
role_type: RoleType = RoleType.ASSISTANT
- meta_dict: Dict[str, str] = None
+ meta_dict: Optional[Dict[str, str]] = None
role: str = "assistant"
content: str = ""
@@ -253,7 +253,7 @@ class UserChatMessage(ChatMessage):
"""
role_name: str
role_type: RoleType = RoleType.USER
- meta_dict: Dict[str, str] = None
+ meta_dict: Optional[Dict[str, str]] = None
role: str = "user"
content: str = ""
diff --git a/camel/utils.py b/camel/utils.py
index 0a5b2552e..4bec48c3c 100644
--- a/camel/utils.py
+++ b/camel/utils.py
@@ -2,7 +2,7 @@ import os
import re
import time
from functools import wraps
-from typing import Any, List, Set
+from typing import Any, Callable, List, Set
import tiktoken
@@ -96,7 +96,7 @@ def get_model_token_limit(model: ModelType) -> int:
return 32768
-def openai_api_key_required(func: callable) -> callable:
+def openai_api_key_required(func: Callable[..., Any]) -> Callable[..., Any]:
r"""Decorator that checks if the OpenAI API key is available in the
environment variables.
@@ -112,7 +112,7 @@ def openai_api_key_required(func: callable) -> callable:
"""
@wraps(func)
- def wrapper(*args, **kwargs):
+ def wrapper(*args, **kwargs) -> Callable[..., Any]:
if 'OPENAI_API_KEY' in os.environ:
return func(*args, **kwargs)
else:
@@ -121,7 +121,7 @@ def openai_api_key_required(func: callable) -> callable:
return wrapper
-def print_text_animated(text, delay=0.02, end=""):
+def print_text_animated(text, delay: float = 0.02, end: str = ""):
r"""Prints the given text with an animated effect.
Args:
diff --git a/examples/ai_society/role_playing_multiprocess.py b/examples/ai_society/role_playing_multiprocess.py
index e0a0c7e3a..b04d69ab3 100644
--- a/examples/ai_society/role_playing_multiprocess.py
+++ b/examples/ai_society/role_playing_multiprocess.py
@@ -34,7 +34,7 @@ def generate_data(assistant_idx: int, assistant_role_name: str, user_idx: int,
print(Fore.BLUE +
f"AI User sys message:\n{role_play_session.user_sys_msg}\n")
- print(Fore.YELLOW + f"Original task prompt:\n{task_prompt}\n")
+ print(Fore.YELLOW + f"Original task prompt:\n{original_task_prompt}\n")
print(Fore.CYAN + "Specified task prompt:\n"
f"{role_play_session.specified_task_prompt}\n")
print(Fore.RED +
@@ -81,19 +81,21 @@ def generate_data(assistant_idx: int, assistant_role_name: str, user_idx: int,
user_msg, user_terminated, user_info = user_return
# Condition 1: User terminates the chat
- if user_terminated:
+ if user_terminated and user_info is not None:
message_dict["termination_reason"] = (
f"{str(user_agent.role_type)}: "
f"{user_info['termination_reasons'][0]}")
break
# Condition 2: Assistant terminates the chat
- if assistant_terminated:
+ if assistant_terminated and assistant_info is not None:
message_dict["termination_reason"] = (
f"{str(assistant_agent.role_type)}: "
f"{assistant_info['termination_reasons'][0]}")
break
+ assert (user_msg is not None) and (assistant_msg is not None)
+
if verbose:
print(f"User:\n{user_msg.content}\n")
print(f"Assistant:\n{assistant_msg.content}\n")
@@ -159,7 +161,12 @@ def main() -> None:
verbose = True
# Chunk for parallel jobs
- array_idx = int(os.environ.get('SLURM_ARRAY_TASK_ID'))
+ try:
+ array_idx = int(os.environ.get('SLURM_ARRAY_TASK_ID'))
+ except (TypeError, ValueError) as e:
+ print(f"Error: {e}")
+ array_idx = 0
+
roles_per_chunk = 10
# Parameters for filtering the generated task string
@@ -177,7 +184,7 @@ def main() -> None:
roles_per_chunk:(array_idx + 1) *
roles_per_chunk]
- pool = multiprocessing.Pool()
+ pool = multiprocessing.Pool(processes=16)
for assistant_idx, assistant_role_name in enumerate(assistant_roles):
assistant_idx += array_idx * roles_per_chunk
diff --git a/examples/ai_society/task_generation.py b/examples/ai_society/task_generation.py
index 2928a760d..d0df08ca2 100644
--- a/examples/ai_society/task_generation.py
+++ b/examples/ai_society/task_generation.py
@@ -12,7 +12,7 @@ from camel.typing import RoleType, TaskType
def generate_tasks(role_names: str, task_generator_prompt: str,
start_token: str = "1.", num_tasks: int = 10) -> None:
- sys_msg_generator = SystemMessageGenerator(task_type=TaskType.DEFAULT)
+ sys_msg_generator = SystemMessageGenerator(task_type=TaskType.AI_SOCIETY)
assistant_sys_msg = sys_msg_generator.from_dict(
dict(), role_tuple=("Task Generator", RoleType.DEFAULT))
@@ -21,7 +21,11 @@ def generate_tasks(role_names: str, task_generator_prompt: str,
user_msg = UserChatMessage(role_name="Task Generator",
content=task_generator_prompt)
- assistant_msgs, _, _ = assistant_agent.step(user_msg)
+ assistant_msgs, assistant_terminated, _ = assistant_agent.step(user_msg)
+
+ if assistant_terminated or assistant_msgs is None:
+ raise RuntimeError("Assistant agent terminated unexpectedly.")
+
assistant_msg = assistant_msgs[0]
tasks = assistant_msg.content.split("\n")
@@ -35,7 +39,8 @@ def generate_tasks(role_names: str, task_generator_prompt: str,
# Ensure exact number of tasks is generated
assert str(num_tasks) in tasks[-1], print(tasks)
- with open(f"./tasks/{'_'.join(role_names)}.txt", "w") as file:
+ with open(f"./ai_society_data/tasks/{'_'.join(role_names)}.txt",
+ "w") as file:
file.write("\n".join(tasks))
@@ -49,7 +54,8 @@ def main() -> None:
pool = multiprocessing.Pool()
for task_generator_prompt, role_names in task_generator_prompt_generator:
- if not os.path.exists(f"./tasks/{'_'.join(role_names)}.txt"):
+ if not os.path.exists(
+ f"./ai_society_data/tasks/{'_'.join(role_names)}.txt"):
print(f"Generating tasks for {role_names}")
pool.apply_async(
generate_tasks,