Skip to content

Commit

Permalink
Merge branch 'master' into remove_role_field
Browse files Browse the repository at this point in the history
  • Loading branch information
Obs01ete committed Jun 26, 2023
2 parents 287dc01 + cde10f8 commit aa963c7
Show file tree
Hide file tree
Showing 6 changed files with 152 additions and 8 deletions.
25 changes: 25 additions & 0 deletions camel/agents/chat_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ class ChatAgent(BaseAgent):
message_window_size (int, optional): The maximum number of previous
messages to include in the context window. If `None`, no windowing
is performed. (default: :obj:`None`)
output_language (str, optional): The language to be output by the
agent. (default: :obj:`None`)
"""

def __init__(
Expand All @@ -92,11 +94,15 @@ def __init__(
model: Optional[ModelType] = None,
model_config: Optional[Any] = None,
message_window_size: Optional[int] = None,
output_language: Optional[str] = None,
) -> None:

self.system_message: BaseMessage = system_message
self.role_name: str = system_message.role_name
self.role_type: RoleType = system_message.role_type
self.output_language: Optional[str] = output_language
if output_language is not None:
self.set_output_language(self.output_language)

self.model: ModelType = (model if model is not None else
ModelType.GPT_3_5_TURBO)
Expand All @@ -122,6 +128,25 @@ def reset(self) -> List[ChatRecord]:
self.init_messages()
return self.stored_messages

def set_output_language(self, output_language: str) -> BaseMessage:
r"""Sets the output language for the system message. This method
updates the output language for the system message. The output
language determines the language in which the output text should be
generated.
Args:
output_language (str): The desired output language.
Returns:
BaseMessage: The updated system message object.
"""
self.output_language = output_language
content = (self.system_message.content +
("\nRegardless of the input language, "
f"you must output text in {output_language}."))
self.system_message = self.system_message.create_new_instance(content)
return self.system_message

def get_info(
self,
id: Optional[str],
Expand Down
14 changes: 12 additions & 2 deletions camel/agents/task_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ class TaskSpecifyAgent(ChatAgent):
the task. (default: :obj:`None`)
word_limit (int): The word limit for the task prompt.
(default: :obj:`50`)
output_language (str, optional): The language to be output by the
agent. (default: :obj:`None`)
"""
DEFAULT_WORD_LIMIT = 50

Expand All @@ -49,6 +51,7 @@ def __init__(
model_config: Optional[Any] = None,
task_specify_prompt: Optional[Union[str, TextPrompt]] = None,
word_limit: int = DEFAULT_WORD_LIMIT,
output_language: str = None,
) -> None:

if task_specify_prompt is None:
Expand All @@ -68,7 +71,9 @@ def __init__(
meta_dict=None,
content="You can make a task more specific.",
)
super().__init__(system_message, model, model_config)

super().__init__(system_message, model, model_config,
output_language=output_language)

def step(
self,
Expand Down Expand Up @@ -122,12 +127,15 @@ class TaskPlannerAgent(ChatAgent):
(default: :obj:`ModelType.GPT_3_5_TURBO`)
model_config (Any): The configuration for the model.
(default: :obj:`None`)
output_language (str, optional): The language to be output by the
agent. (default: :obj:`None`)
"""

def __init__(
self,
model: Optional[ModelType] = None,
model_config: Any = None,
output_language: str = None,
) -> None:

self.task_planner_prompt = TextPrompt(
Expand All @@ -139,7 +147,9 @@ def __init__(
meta_dict=None,
content="You are a helpful task planner.",
)
super().__init__(system_message, model, model_config)

super().__init__(system_message, model, model_config,
output_language=output_language)

def step(
self,
Expand Down
6 changes: 3 additions & 3 deletions camel/messages/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def make_assistant_message(
meta_dict: Optional[Dict[str, str]] = None) -> 'BaseMessage':
return cls(role_name, RoleType.ASSISTANT, meta_dict, content)

def _create_new_instance(self, content: str) -> "BaseMessage":
def create_new_instance(self, content: str) -> "BaseMessage":
r"""Create a new instance of the :obj:`BaseMessage` with updated
content.
Expand Down Expand Up @@ -87,7 +87,7 @@ def __add__(self, other: Any) -> Union["BaseMessage", Any]:
raise TypeError(
f"Unsupported operand type(s) for +: '{type(self)}' and "
f"'{type(other)}'")
return self._create_new_instance(combined_content)
return self.create_new_instance(combined_content)

def __mul__(self, other: Any) -> Union["BaseMessage", Any]:
r"""Multiplication operator override for :obj:`BaseMessage`.
Expand All @@ -100,7 +100,7 @@ def __mul__(self, other: Any) -> Union["BaseMessage", Any]:
"""
if isinstance(other, int):
multiplied_content = self.content.__mul__(other)
return self._create_new_instance(multiplied_content)
return self.create_new_instance(multiplied_content)
else:
raise TypeError(
f"Unsupported operand type(s) for *: '{type(self)}' and "
Expand Down
16 changes: 13 additions & 3 deletions camel/societies/role_playing.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ class RolePlaying:
extend the system message meta dicts with. (default: :obj:`None`)
extend_task_specify_meta_dict (Dict, optional): A dict to extend the
task specify meta dict with. (default: :obj:`None`)
output_language (str, optional): The language to be output by the
agents. (default: :obj:`None`)
"""

def __init__(
Expand All @@ -85,6 +87,7 @@ def __init__(
sys_msg_generator_kwargs: Optional[Dict] = None,
extend_sys_msg_meta_dicts: Optional[List[Dict]] = None,
extend_task_specify_meta_dict: Optional[Dict] = None,
output_language: str = None,
) -> None:
self.with_task_specify = with_task_specify
self.with_task_planner = with_task_planner
Expand All @@ -104,6 +107,7 @@ def __init__(
task_specify_agent = TaskSpecifyAgent(
self.model_type,
task_type=self.task_type,
output_language=output_language,
**(task_specify_agent_kwargs or {}),
)
self.specified_task_prompt = task_specify_agent.step(
Expand All @@ -117,6 +121,7 @@ def __init__(
if with_task_planner:
task_planner_agent = TaskPlannerAgent(
self.model_type,
output_language=output_language,
**(task_planner_agent_kwargs or {}),
)
self.planned_task_prompt = task_planner_agent.step(task_prompt)
Expand All @@ -143,7 +148,7 @@ def __init__(
} for sys_msg_meta_dict, extend_sys_msg_meta_dict in zip(
sys_msg_meta_dicts, extend_sys_msg_meta_dicts)]

self.assistant_sys_msg, self.user_sys_msg = (
init_assistant_sys_msg, init_user_sys_msg = (
sys_msg_generator.from_dicts(
meta_dicts=sys_msg_meta_dicts,
role_tuples=[
Expand All @@ -153,15 +158,20 @@ def __init__(
))

self.assistant_agent: ChatAgent = ChatAgent(
self.assistant_sys_msg,
init_assistant_sys_msg,
model_type,
output_language=output_language,
**(assistant_agent_kwargs or {}),
)
self.assistant_sys_msg = self.assistant_agent.system_message

self.user_agent: ChatAgent = ChatAgent(
self.user_sys_msg,
init_user_sys_msg,
model_type,
output_language=output_language,
**(user_agent_kwargs or {}),
)
self.user_sys_msg = self.user_agent.system_message

if with_critic_in_the_loop:
if critic_role_name.lower() == "human":
Expand Down
75 changes: 75 additions & 0 deletions examples/ai_society/role_playing_multi_lingual.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
# Licensed under the Apache License, Version 2.0 (the “License”);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an “AS IS” BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
from colorama import Fore

from camel.societies import RolePlaying
from camel.utils import print_text_animated


def main(model_type=None) -> None:
task_prompt = "Develop a trading bot for the stock market"
role_play_session = RolePlaying(
"Python Programmer",
"Stock Trader",
task_prompt=task_prompt,
with_task_specify=True,
model_type=model_type,
output_language="Chinese", # Arabic, French, Spanish, ...
)

print(
Fore.GREEN +
f"AI Assistant sys message:\n{role_play_session.assistant_sys_msg}\n")
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.CYAN +
f"Specified task prompt:\n{role_play_session.specified_task_prompt}\n")
print(Fore.RED + f"Final task prompt:\n{role_play_session.task_prompt}\n")

chat_turn_limit, n = 50, 0
input_assistant_msg, _ = role_play_session.init_chat()
while n < chat_turn_limit:
n += 1
assistant_response, user_response = role_play_session.step(
input_assistant_msg)

input_assistant_msg = assistant_response.msg

if assistant_response.terminated:
print(Fore.GREEN +
("AI Assistant terminated. Reason: "
f"{assistant_response.info['termination_reasons']}."))
break
if user_response.terminated:
print(Fore.GREEN +
("AI User terminated. "
f"Reason: {user_response.info['termination_reasons']}."))
break

print_text_animated(Fore.BLUE +
f"AI User:\n\n{user_response.msg.content}\n")
print_text_animated(Fore.GREEN + "AI Assistant:\n\n"
f"{assistant_response.msg.content}\n")

if "CAMEL_TASK_DONE" in user_response.msg.content:
break


if __name__ == "__main__":
from camel.typing import ModelType

main(ModelType.GPT_4)
24 changes: 24 additions & 0 deletions test/agents/test_chat_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,3 +81,27 @@ def test_chat_agent_multiple_return_messages(n):
assistant_response = assistant.step(user_msg)
assert assistant_response.msgs is not None
assert len(assistant_response.msgs) == n


@pytest.mark.model_backend
def test_set_output_language():
system_message = BaseMessage(role_name="assistant",
role_type=RoleType.ASSISTANT,
content="You are a help assistant.")
agent = ChatAgent(system_message=system_message,
model=ModelType.GPT_3_5_TURBO)
assert agent.output_language is None

# Set the output language to "Arabic"
output_language = "Arabic"
agent.set_output_language(output_language)

# Check if the output language is set correctly
assert agent.output_language == output_language

# Verify that the system message is updated with the new output language
updated_system_message = BaseMessage(
role_name="assistant", role_type="assistant",
content="You are a help assistant."
"\nRegardless of the input language, you must output text in Arabic.")
assert agent.system_message.content == updated_system_message.content

0 comments on commit aa963c7

Please sign in to comment.