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

Cleanup mypy errors (#160)

Dmitrii Khizbullina38fdafcf7e8
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 387ad4dd7..20067ae3a 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -78,6 +78,15 @@ flake8
isort .
```
+For extra validation of type hints:
+
+```bash
+mypy --namespace-packages -p camel
+mypy --namespace-packages -p test
+mypy --namespace-packages -p examples
+mypy --namespace-packages -p apps
+```
+
### Coverage 📊
Code coverage measures the extent to which unit tests cover the code, helping identify both robust and less robust areas of the codebase.
diff --git a/camel/agents/critic_agent.py b/camel/agents/critic_agent.py
index 95bd1137f..92b097cd6 100644
--- a/camel/agents/critic_agent.py
+++ b/camel/agents/critic_agent.py
@@ -14,7 +14,7 @@
import copy
import random
import warnings
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, Optional, Sequence
from colorama import Fore
@@ -61,11 +61,11 @@ class CriticAgent(ChatAgent):
self.verbose = verbose
self.logger_color = logger_color
- def flatten_options(self, messages: List[ChatMessage]) -> str:
+ def flatten_options(self, messages: Sequence[ChatMessage]) -> str:
r"""Flattens the options to the critic.
Args:
- messages (List[ChatMessage]): A list of `ChatMessage` objects.
+ messages (Sequence[ChatMessage]): A list of `ChatMessage` objects.
Returns:
str: A string containing the flattened options to the critic.
@@ -142,12 +142,12 @@ class CriticAgent(ChatAgent):
choice = str(get_first_int(critic_msg.content))
return choice
- def step(self, messages: List[ChatMessage]) -> ChatMessage:
+ def step(self, messages: Sequence[ChatMessage]) -> ChatMessage:
r"""Performs one step of the conversation by flattening options to the
critic, getting the option, and parsing the choice.
Args:
- messages (List[ChatMessage]): A list of ChatMessage objects.
+ messages (Sequence[ChatMessage]): A list of ChatMessage objects.
Returns:
ChatMessage: A `ChatMessage` object representing the critic's
@@ -168,7 +168,7 @@ class CriticAgent(ChatAgent):
input_msg = copy.deepcopy(meta_chat_message)
input_msg.content = flatten_options
- option = self.get_option(input_msg.to_user_chat_message())
+ option = self.get_option(input_msg.set_user_role_at_backend())
output_msg = copy.deepcopy(meta_chat_message)
output_msg.content = option
diff --git a/camel/agents/role_playing.py b/camel/agents/role_playing.py
index eba0931c9..be96767e4 100644
--- a/camel/agents/role_playing.py
+++ b/camel/agents/role_playing.py
@@ -11,7 +11,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
-from typing import Dict, List, Optional, Tuple
+from typing import Dict, List, Optional, Sequence, Tuple
from camel.agents import (
ChatAgent,
@@ -200,7 +200,7 @@ class RolePlaying:
# Send the system messages again to the agents using chat messages
assistant_msg = AssistantChatMessage(
- role_name=self.assistant_sys_msg.role_name,
+ role_name=self.assistant_sys_msg.role_name, role="assistant",
content=(f"{self.user_sys_msg.content}. "
"Now start to give me instructions one by one. "
"Only reply with Instruction and Input."))
@@ -216,7 +216,7 @@ class RolePlaying:
def process_messages(
self,
- messages: List[ChatMessage],
+ messages: Sequence[ChatMessage],
) -> ChatMessage:
r"""Processes a list of chat messages, returning the processed message.
If multiple messages are provided and `with_critic_in_the_loop`
@@ -266,8 +266,8 @@ class RolePlaying:
whether or not the user agent terminated the conversation, and
any additional user information.
"""
- user_response = self.user_agent.step(
- assistant_msg.to_user_chat_message())
+ assistant_msg_rst = assistant_msg.set_user_role_at_backend()
+ user_response = self.user_agent.step(assistant_msg_rst)
if user_response.terminated or user_response.msgs is None:
return (ChatAgentResponse([], False, {}),
ChatAgentResponse([], user_response.terminated,
@@ -275,8 +275,8 @@ class RolePlaying:
user_msg = self.process_messages(user_response.msgs)
self.user_agent.update_messages(user_msg)
- assistant_response = self.assistant_agent.step(
- user_msg.to_user_chat_message())
+ user_msg_rst = user_msg.set_user_role_at_backend()
+ assistant_response = self.assistant_agent.step(user_msg_rst)
if assistant_response.terminated or assistant_response.msgs is None:
return (ChatAgentResponse([], assistant_response.terminated,
assistant_response.info),
diff --git a/camel/configs.py b/camel/configs.py
index e2d802082..1b90e33ac 100644
--- a/camel/configs.py
+++ b/camel/configs.py
@@ -15,7 +15,7 @@ from dataclasses import dataclass, field
from typing import Dict, Optional, Sequence, Union
-@dataclass
+@dataclass(frozen=True)
class ChatGPTConfig:
r"""Defines the parameters for generating chat completions using the
OpenAI API.
diff --git a/camel/generators.py b/camel/generators.py
index 0c6b64e88..cc9d6ec91 100644
--- a/camel/generators.py
+++ b/camel/generators.py
@@ -14,7 +14,7 @@
from typing import Dict, Generator, List, Optional, Set, Tuple
from camel.messages import SystemMessage, SystemMessageType
-from camel.prompts import PromptTemplateGenerator
+from camel.prompts import PromptTemplateGenerator, TextPrompt
from camel.typing import RoleType, TaskType
@@ -37,6 +37,8 @@ class SystemMessageGenerator:
sys_prompts: Optional[Dict[RoleType, str]] = None,
sys_msg_meta_dict_keys: Optional[Set[str]] = None,
) -> None:
+ self.sys_prompts: Dict[RoleType, str]
+
if sys_prompts is not None:
self.sys_prompts = sys_prompts
self.sys_msg_meta_dict_keys = sys_msg_meta_dict_keys or set()
@@ -61,7 +63,7 @@ class SystemMessageGenerator:
RoleType.EMBODIMENT,
)
- self.sys_prompts: Dict[RoleType, str] = dict()
+ self.sys_prompts = dict()
self.sys_prompts[RoleType.ASSISTANT] = assistant_prompt_template
self.sys_prompts[RoleType.USER] = user_prompt_template
self.sys_prompts[RoleType.CRITIC] = critic_prompt_template
@@ -150,19 +152,19 @@ class RoleNameGenerator:
if assistant_role_names is None:
with open(assistant_role_names_path, "r") as f:
- assistant_role_names: List[str] = f.read().splitlines()
+ assistant_role_names_: List[str] = f.read().splitlines()
self.assistant_role_names = [
" ".join(name.split(" ")[1:])
- for name in assistant_role_names
+ for name in assistant_role_names_
]
else:
self.assistant_role_names = assistant_role_names
if user_role_names is None:
with open(user_role_names_path, "r") as f:
- user_role_names: List[str] = f.read().splitlines()
+ user_role_names_: List[str] = f.read().splitlines()
self.user_role_names = [
- " ".join(name.split(" ")[1:]) for name in user_role_names
+ " ".join(name.split(" ")[1:]) for name in user_role_names_
]
else:
self.user_role_names = user_role_names
@@ -223,7 +225,7 @@ class SingleTxtGenerator:
" ".join(name.split(" ")[1:]) for name in data_list
]
- def from_role_files(self) -> Generator[Tuple, None, None]:
+ def from_role_files(self) -> Generator[str, None, None]:
for data in self.data_list:
yield data
@@ -243,7 +245,7 @@ class CodeTaskPromptGenerator:
def from_role_files(
self, languages_path: str = "data/code/languages.txt",
domains_path: str = "data/code/domains.txt"
- ) -> Generator[Tuple[str, str, str], None, None]:
+ ) -> Generator[Tuple[TextPrompt, str, str], None, None]:
language_generator = SingleTxtGenerator(
languages_path).from_role_files()
@@ -253,7 +255,7 @@ class CodeTaskPromptGenerator:
for domain in domains_generator:
generated_tasks_prompt = self.generate_tasks_prompt.format(
language=language, domain=domain, num_tasks=self.num_tasks)
- yield (generated_tasks_prompt, language, domain)
+ yield generated_tasks_prompt, language, domain
def from_role_generator(
self, role_generator: Generator[Tuple, None, None]
diff --git a/camel/human.py b/camel/human.py
index 8e6faeb8f..07321e35e 100644
--- a/camel/human.py
+++ b/camel/human.py
@@ -11,7 +11,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
-from typing import Any, Dict, List
+from typing import Any, Dict, Sequence
from colorama import Fore
@@ -46,11 +46,11 @@ class Human:
self.kill_button = "Stop!!!"
self.options_dict: Dict[str, str] = dict()
- def display_options(self, messages: List[ChatMessage]) -> None:
+ def display_options(self, messages: Sequence[ChatMessage]) -> None:
r"""Displays the options to the user.
Args:
- messages (List[ChatMessage]): A list of `ChatMessage` objects.
+ messages (Sequence[ChatMessage]): A list of `ChatMessage` objects.
Returns:
None
@@ -107,12 +107,12 @@ class Human:
meta_chat_message.content = self.options_dict[human_input]
return meta_chat_message
- def step(self, messages: List[ChatMessage]) -> ChatMessage:
+ def step(self, messages: Sequence[ChatMessage]) -> ChatMessage:
r"""Performs one step of the conversation by displaying options to the
user, getting their input, and parsing their choice.
Args:
- messages (List[ChatMessage]): A list of ChatMessage objects.
+ messages (Sequence[ChatMessage]): A list of ChatMessage objects.
Returns:
ChatMessage: A `ChatMessage` object representing the user's choice.
diff --git a/camel/messages/base.py b/camel/messages/base.py
index 89c951ebd..16c84e43f 100644
--- a/camel/messages/base.py
+++ b/camel/messages/base.py
@@ -12,7 +12,7 @@
# limitations under the License.
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
from dataclasses import dataclass
-from typing import Any, Dict, List, Optional, Tuple, Type, Union
+from typing import Any, Dict, List, Optional, Tuple, Union
from camel.messages import (
OpenAIAssistantMessage,
@@ -226,38 +226,6 @@ class BaseMessage:
return text_prompts, code_prompts
- def to_user_chat_message(self) -> Type["UserChatMessage"]: # noqa: F821
- r"""Converts the message to a :obj:`UserChatMessage` object.
-
- Returns:
- UserChatMessage: The converted :obj:`UserChatMessage` object.
- """
- from camel.messages.chat_messages import UserChatMessage
-
- return UserChatMessage(
- role_name=self.role_name,
- role_type=self.role_type,
- meta_dict=self.meta_dict,
- content=self.content,
- )
-
- def to_assistant_chat_message(
- self) -> Type["AssistantChatMessage"]: # noqa: F821
- r"""Converts the message to an :obj:`AssistantChatMessage` object.
-
- Returns:
- AssistantChatMessage: The converted :obj:`AssistantChatMessage`
- object.
- """
- from camel.messages.chat_messages import AssistantChatMessage
-
- return AssistantChatMessage(
- role_name=self.role_name,
- role_type=self.role_type,
- meta_dict=self.meta_dict,
- content=self.content,
- )
-
def to_openai_message(self, role: Optional[str] = None) -> OpenAIMessage:
r"""Converts the message to an :obj:`OpenAIMessage` object.
diff --git a/camel/messages/chat_messages.py b/camel/messages/chat_messages.py
index 174abcad4..1a9406344 100644
--- a/camel/messages/chat_messages.py
+++ b/camel/messages/chat_messages.py
@@ -37,6 +37,15 @@ class ChatMessage(BaseMessage):
role: str
content: str = ""
+ def set_user_role_at_backend(self: BaseMessage):
+ return self.__class__(
+ role_name=self.role_name,
+ role_type=self.role_type,
+ meta_dict=self.meta_dict,
+ role="user",
+ content=self.content,
+ )
+
@dataclass
class AssistantChatMessage(ChatMessage):
@@ -56,7 +65,7 @@ class AssistantChatMessage(ChatMessage):
role_name: str
role_type: RoleType = RoleType.ASSISTANT
meta_dict: Optional[Dict[str, str]] = None
- role: str = "assistant"
+ role: str = "user"
content: str = ""
diff --git a/camel/prompts/base.py b/camel/prompts/base.py
index 776a7c629..6b0aec105 100644
--- a/camel/prompts/base.py
+++ b/camel/prompts/base.py
@@ -161,7 +161,9 @@ class CodePrompt(TextPrompt):
"""
self._code_type = code_type
- def execute(self, global_vars: Dict = None) -> Tuple[str, Optional[Dict]]:
+ def execute(
+ self,
+ global_vars: Optional[Dict] = None) -> Tuple[str, Optional[Dict]]:
r"""Executes the code string. If there is an error, the error is caught
and the traceback is returned. Otherwise, the output string and local
variables are returned.
diff --git a/camel/prompts/prompt_templates.py b/camel/prompts/prompt_templates.py
index f0cf38c42..005fb94e8 100644
--- a/camel/prompts/prompt_templates.py
+++ b/camel/prompts/prompt_templates.py
@@ -12,7 +12,7 @@
# limitations under the License.
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
import warnings
-from typing import Any
+from typing import Any, Optional
from camel.prompts import TaskPromptTemplateDict, TextPrompt
from camel.typing import RoleType, TaskType
@@ -29,7 +29,7 @@ class PromptTemplateGenerator:
def __init__(
self,
- task_prompt_template_dict: TaskPromptTemplateDict = None,
+ task_prompt_template_dict: Optional[TaskPromptTemplateDict] = None,
) -> None:
self.task_prompt_template_dict = (task_prompt_template_dict
or TaskPromptTemplateDict())
diff --git a/camel/utils.py b/camel/utils.py
index e379a1999..db4b0a2bd 100644
--- a/camel/utils.py
+++ b/camel/utils.py
@@ -79,6 +79,7 @@ def num_tokens_from_messages(
encoding = tiktoken.encoding_for_model(model.value)
except KeyError:
encoding = tiktoken.get_encoding("cl100k_base")
+
if model == ModelType.GPT_3_5_TURBO:
return count_tokens_openai_chat_models(messages, encoding)
elif model == ModelType.GPT_4:
@@ -111,6 +112,8 @@ def get_model_token_limit(model: ModelType) -> int:
return 8192
if model == ModelType.GPT_4_32k:
return 32768
+ else:
+ raise ValueError("Unknown model type")
def openai_api_key_required(func: F) -> F:
diff --git a/examples/code/role_playing_multiprocess.py b/examples/code/role_playing_multiprocess.py
index 9110646d3..446b919fd 100644
--- a/examples/code/role_playing_multiprocess.py
+++ b/examples/code/role_playing_multiprocess.py
@@ -39,7 +39,7 @@ def init_chat(
# Send the system messages again to the agents using chat messages
assistant_msg = AssistantChatMessage(
- role_name=assistant_agent.role_name,
+ role_name=assistant_agent.role_name, role="assistant",
content=(f"{user_sys_msg.content}. "
"Now start to give me instructions one by one. "
"Only reply with Instruction and Input."))
@@ -125,7 +125,8 @@ def generate_data(language_idx: int, language_name: str, domain_idx: int,
while message_counter < max_num_messages:
- user_response = user_agent.step(assistant_msg.to_user_chat_message())
+ user_response = user_agent.step(
+ assistant_msg.set_user_role_at_backend())
# Condition 1: User terminates the chat
if user_response.terminated:
@@ -138,7 +139,7 @@ def generate_data(language_idx: int, language_name: str, domain_idx: int,
print(f"User:\n{user_response.msg.content}\n")
assistant_response = assistant_agent.step(
- user_response.msg.to_user_chat_message())
+ user_response.msg.set_user_role_at_backend())
# Condition 2: Assistant terminates the chat
if assistant_response.terminated:
diff --git a/test/agents/test_role_playing.py b/test/agents/test_role_playing.py
index fd25ddeae..739d48425 100644
--- a/test/agents/test_role_playing.py
+++ b/test/agents/test_role_playing.py
@@ -63,14 +63,15 @@ def test_role_playing_init():
def test_role_playing_step(task_type, extend_sys_msg_meta_dicts,
extend_task_specify_meta_dict):
role_playing = RolePlaying(
- assistant_role_name="assistant",
- user_role_name="user",
+ assistant_role_name="AI Assistant",
+ user_role_name="AI User",
task_prompt="Perform the task",
task_type=task_type,
extend_sys_msg_meta_dicts=extend_sys_msg_meta_dicts,
extend_task_specify_meta_dict=extend_task_specify_meta_dict,
)
- init_assistant_msg = AssistantChatMessage(role_name="assistant",
+ init_assistant_msg = AssistantChatMessage(role_name="AI Assistant",
+ role="assistant",
content="Hello")
print(role_playing.assistant_agent.system_message)
print(role_playing.user_agent.system_message)
diff --git a/test/messages/test_chat_message.py b/test/messages/test_chat_message.py
index 101284cb1..738fc9f72 100644
--- a/test/messages/test_chat_message.py
+++ b/test/messages/test_chat_message.py
@@ -34,6 +34,7 @@ def assistant_chat_message() -> AssistantChatMessage:
role_name="test_assistant",
role_type=RoleType.ASSISTANT,
meta_dict=None,
+ role="assistant",
content="test assistant chat message",
)
diff --git a/test/messages/test_message_base.py b/test/messages/test_message_base.py
index 2a308985c..0f37cccb7 100644
--- a/test/messages/test_message_base.py
+++ b/test/messages/test_message_base.py
@@ -110,20 +110,6 @@ def test_base_message():
assert message.role == role
assert message.content == content
- user_message = message.to_user_chat_message()
- assert user_message.role_name == role_name
- assert user_message.role_type == role_type
- assert user_message.meta_dict == meta_dict
- assert user_message.role == "user"
- assert user_message.content == content
-
- assistant_message = message.to_assistant_chat_message()
- assert assistant_message.role_name == role_name
- assert assistant_message.role_type == role_type
- assert assistant_message.meta_dict == meta_dict
- assert assistant_message.role == "assistant"
- assert assistant_message.content == content
-
openai_message = message.to_openai_message()
assert openai_message == {"role": role, "content": content}