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

Babyagi agent support (#243)

Hongyi Chen50c9c97a1b1d
diff --git a/camel/agents/task_agent.py b/camel/agents/task_agent.py
index 06270d8e7..4cbaed118 100644
--- a/camel/agents/task_agent.py
+++ b/camel/agents/task_agent.py
@@ -189,10 +189,11 @@ class TaskCreationAgent(ChatAgent):
`BabyAGI <https://github.com/yoheinakajima/babyagi>`_.
Attributes:
- task_creation_prompt (TextPrompt): A prompt for the agent to create
- new tasks.
+ task_creation_prompt (TextPrompt): A prompt for the agent to
+ create new tasks.
Args:
+ role_name (str): The role name of the Agent to create the task.
objective (Union[str, TextPrompt]): The objective of the Agent to
perform the task.
model (ModelType, optional): The type of model to use for the agent.
@@ -201,36 +202,47 @@ class TaskCreationAgent(ChatAgent):
(default: :obj:`None`)
output_language (str, optional): The language to be output by the
agent. (default: :obj:`None`)
+ 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`)
+ max_task_num (int, optional): The maximum number of planned
+ tasks in one round. (default: :obj:3)
"""
def __init__(
self,
+ role_name: str,
objective: Union[str, TextPrompt],
model: Optional[ModelType] = None,
model_config: Optional[Any] = None,
output_language: Optional[str] = None,
+ message_window_size: Optional[int] = None,
+ max_task_num: Optional[int] = 3,
) -> None:
task_creation_prompt = TextPrompt(
- """Create new tasks with the following objective: {objective}.
-The last completed task has the result:
-{task_result}.
-This result was based on this task: {task}.
-Based on the result, return a list of tasks to be completed in order to meet \
-the objective.
-
-{unsolved_tasks}
-
-Return one task per line in your response.
+ """Create new a task with the following objective: {objective}.
+Never forget you are a Task Creator of {role_name}.
+You must instruct me based on my expertise and your needs to solve the task.
+You should consider past solved tasks and in-progress tasks: {task_list}.
+The new created tasks must not overlap with these past tasks.
The result must be a numbered list in the format:
-1. First task
-2. Second task
+ #. First Task
+ #. Second Task
+ #. Third Task
-The number of each entry must be followed by a period. Be concise.""")
+You can only give me up to {max_task_num} tasks at a time. \
+Each task shoud be concise, concrete and doable for a {role_name}.
+You should make task plan and not ask me questions.
+If you think no new tasks are needed right now, write "No tasks to add."
+Now start to give me new tasks one by one. No more than three tasks.
+Be concrete.
+""")
self.task_creation_prompt = task_creation_prompt.format(
- objective=objective)
+ objective=objective, role_name=role_name,
+ max_task_num=max_task_num)
self.objective = objective
system_message = BaseMessage(
@@ -241,45 +253,32 @@ The number of each entry must be followed by a period. Be concise.""")
)
super().__init__(system_message, model, model_config,
- output_language=output_language)
+ output_language=output_language,
+ message_window_size=message_window_size)
def run(
self,
- previous_task: Union[str, TextPrompt],
- task_result: Union[str, TextPrompt],
- task_list: Optional[List[str]] = None,
+ task_list: List[str],
) -> List[str]:
r"""Generate subtasks based on the previous task results and
incomplete task list.
Args:
- previous_task (Union[str, TextPrompt]): The last completed task to
- be used to create future plans.
- task_result (Union[str, TextPrompt]): The result of last completed
- task to be used to create future plans.
- task_list (List[str], optional): The incomplete task list
- which should not overlap with new created tasks.
- (default: :obj:`None`)
+ task_list (List[str]): The completed or in-progress
+ tasks which should not overlap with new created tasks.
Returns:
List[str]: The new task list generated by the Agent.
"""
- self.reset()
- task_creation_prompt = self.task_creation_prompt.format(
- task=previous_task, task_result=task_result)
- if task_list is not None:
- unsolved = (
- f"These are unsolved tasks: {task_list}.\n"
- "These new tasks must not overlap with incomplete tasks.")
-
- task_creation_prompt = task_creation_prompt.format(
- unsolved_tasks=unsolved)
+
+ if len(task_list) > 0:
+ task_creation_prompt = self.task_creation_prompt.format(
+ task_list=task_list)
else:
- task_creation_prompt = task_creation_prompt.format(
- unsolved_tasks="")
+ task_creation_prompt = self.task_creation_prompt.format(
+ task_list="")
task_msg = BaseMessage.make_user_message(role_name="Task Creator",
content=task_creation_prompt)
-
task_response = self.step(task_msg)
if len(task_response.msgs) == 0:
@@ -309,6 +308,9 @@ class TaskPrioritizationAgent(ChatAgent):
(default: :obj:`None`)
output_language (str, optional): The language to be output by the
agent. (default: :obj:`None`)
+ 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`)
"""
def __init__(
@@ -317,23 +319,24 @@ class TaskPrioritizationAgent(ChatAgent):
model: Optional[ModelType] = None,
model_config: Optional[Any] = None,
output_language: Optional[str] = None,
+ message_window_size: Optional[int] = None,
) -> None:
-
task_prioritization_prompt = TextPrompt(
"""Prioritize the following tasks : {task_list}.
Consider the ultimate objective of you: {objective}.
-Tasks should be sorted from highest to lowest priority,
-where higher-priority tasks are those that act as pre-requisites \
-or are more essential for meeting the objective.
-Return one task per line in your response. Do not remove any tasks.
+Tasks should be sorted from highest to lowest priority, where higher-priority \
+tasks are those that act as pre-requisites or are more essential for meeting \
+the objective. Return one task per line in your response.
+Do not remove or modify any tasks.
The result must be a numbered list in the format:
-1. First task
-2. Second task
+ #. First task
+ #. Second task
The entries must be consecutively numbered, starting with 1.
The number of each entry must be followed by a period.
-Be concise.""")
+Do not include any headers before your ranked list or follow your list \
+with any other output.""")
self.task_prioritization_prompt = task_prioritization_prompt.format(
objective=objective)
@@ -347,7 +350,8 @@ Be concise.""")
)
super().__init__(system_message, model, model_config,
- output_language=output_language)
+ output_language=output_language,
+ message_window_size=message_window_size)
def run(
self,
@@ -356,11 +360,10 @@ Be concise.""")
r"""Prioritize the task list given the agent objective.
Args:
- task_list (List[str]): The un-prioritized task list of agent.
+ task_list (List[str]): The unprioritized tasks of agent.
Returns:
List[str]: The new prioritized task list generated by the Agent.
"""
- self.reset()
task_prioritization_prompt = self.task_prioritization_prompt.format(
task_list=task_list)
diff --git a/camel/societies/__init__.py b/camel/societies/__init__.py
index b73b6f692..604ebde65 100644
--- a/camel/societies/__init__.py
+++ b/camel/societies/__init__.py
@@ -12,7 +12,9 @@
# limitations under the License.
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
from .role_playing import RolePlaying
+from .babyagi_playing import BabyAGI
__all__ = [
'RolePlaying',
+ 'BabyAGI',
]
diff --git a/camel/societies/babyagi_playing.py b/camel/societies/babyagi_playing.py
new file mode 100644
index 000000000..b5803d7a0
--- /dev/null
+++ b/camel/societies/babyagi_playing.py
@@ -0,0 +1,253 @@
+# =========== 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 collections import deque
+from typing import Dict, List, Optional
+
+from camel.agents import (
+ ChatAgent,
+ TaskCreationAgent,
+ TaskPrioritizationAgent,
+ TaskSpecifyAgent,
+)
+from camel.agents.chat_agent import ChatAgentResponse
+from camel.generators import SystemMessageGenerator
+from camel.messages import BaseMessage
+from camel.prompts import TextPrompt
+from camel.typing import RoleType, TaskType
+
+
+class BabyAGI:
+ r"""BabyAGI Agent.
+
+ Args:
+ assistant_role_name (str): The name of the role played by the
+ assistant.
+ user_role_name (str): The name of the role played by the user.
+ task_prompt (str, optional): A prompt for the task to be performed.
+ (default: :obj:`""`)
+ task_type (TaskType, optional): The type of task to perform.
+ (default: :obj:`TaskType.AI_SOCIETY`)
+ max_task_history (int): The maximum number of previous tasks
+ information to include in the task agent.
+ (default: :obj:10)
+ assistant_agent_kwargs (Dict, optional): Additional arguments to pass
+ to the assistant agent. (default: :obj:`None`)
+ task_specify_agent_kwargs (Dict, optional): Additional arguments to
+ pass to the task specify agent. (default: :obj:`None`)
+ task_creation_agent_kwargs (Dict, optional): Additional arguments to
+ pass to the task creation agent. (default: :obj:`None`)
+ task_prioritization_agent_kwargs (Dict, optional): Additional arguments
+ to pass to the task prioritization agent. (default: :obj:`None`)
+ sys_msg_generator_kwargs (Dict, optional): Additional arguments to
+ pass to the system message generator. (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`)
+ 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`)
+ """
+
+ def __init__(
+ self,
+ assistant_role_name: str,
+ user_role_name: str,
+ task_prompt: str = "",
+ task_type: TaskType = TaskType.AI_SOCIETY,
+ max_task_history: int = 10,
+ assistant_agent_kwargs: Optional[Dict] = None,
+ task_specify_agent_kwargs: Optional[Dict] = None,
+ task_creation_agent_kwargs: Optional[Dict] = None,
+ task_prioritization_agent_kwargs: Optional[Dict] = None,
+ sys_msg_generator_kwargs: Optional[Dict] = None,
+ extend_task_specify_meta_dict: Optional[Dict] = None,
+ output_language: Optional[str] = None,
+ message_window_size: Optional[int] = None,
+ ) -> None:
+ self.task_type = task_type
+ self.task_prompt = task_prompt
+ self.specified_task_prompt: TextPrompt
+ self.init_specified_task_prompt(assistant_role_name, user_role_name,
+ task_specify_agent_kwargs,
+ extend_task_specify_meta_dict,
+ output_language)
+
+ sys_msg_generator = SystemMessageGenerator(
+ task_type=self.task_type, **(sys_msg_generator_kwargs or {}))
+
+ init_assistant_sys_msg = sys_msg_generator.from_dicts(
+ meta_dicts=[
+ dict(
+ assistant_role=assistant_role_name,
+ user_role=user_role_name,
+ task=self.specified_task_prompt,
+ )
+ ],
+ role_tuples=[
+ (assistant_role_name, RoleType.ASSISTANT),
+ ],
+ )
+
+ self.assistant_agent: ChatAgent
+ self.assistant_sys_msg: BaseMessage
+ self.task_creation_agent: TaskCreationAgent
+ self.task_prioritization_agent: TaskPrioritizationAgent
+ self.init_agents(init_assistant_sys_msg[0], assistant_agent_kwargs,
+ task_creation_agent_kwargs,
+ task_prioritization_agent_kwargs, output_language,
+ message_window_size)
+
+ self.subtasks: deque = deque([])
+ self.solved_subtasks: List[str] = []
+ self.MAX_TASK_HISTORY = max_task_history
+
+ def init_specified_task_prompt(
+ self, assistant_role_name: str, user_role_name: str,
+ task_specify_agent_kwargs: Optional[Dict],
+ extend_task_specify_meta_dict: Optional[Dict],
+ output_language: Optional[str]):
+ r"""Use a task specify agent to generate a specified task prompt.
+ Generated specified task prompt will be used to replace original
+ task prompt. If there is no task specify agent, specified task
+ prompt will not be generated.
+
+ Args:
+ assistant_role_name (str): The name of the role played by the
+ assistant.
+ user_role_name (str): The name of the role played by the user.
+ task_specify_agent_kwargs (Dict, optional): Additional arguments
+ to pass to the task specify agent.
+ extend_task_specify_meta_dict (Dict, optional): A dict to extend
+ the task specify meta dict with.
+ output_language (str, optional): The language to be output by the
+ agents.
+ """
+ task_specify_meta_dict = dict()
+ if self.task_type in [TaskType.AI_SOCIETY, TaskType.MISALIGNMENT]:
+ task_specify_meta_dict.update(
+ dict(assistant_role=assistant_role_name,
+ user_role=user_role_name))
+ task_specify_meta_dict.update(extend_task_specify_meta_dict or {})
+ task_specify_agent = TaskSpecifyAgent(
+ task_type=self.task_type,
+ output_language=output_language,
+ **(task_specify_agent_kwargs or {}),
+ )
+ self.specified_task_prompt = task_specify_agent.run(
+ self.task_prompt,
+ meta_dict=task_specify_meta_dict,
+ )
+
+ def init_agents(self, init_assistant_sys_msg: BaseMessage,
+ assistant_agent_kwargs: Optional[Dict],
+ task_creation_agent_kwargs: Optional[Dict],
+ task_prioritization_agent_kwargs: Optional[Dict],
+ output_language: Optional[str],
+ message_window_size: Optional[int] = None):
+ r"""Initialize assistant and user agents with their system messages.
+
+ Args:
+ init_assistant_sys_msg (BaseMessage): Assistant agent's initial
+ system message.
+ assistant_agent_kwargs (Dict, optional): Additional arguments to
+ pass to the assistant agent.
+ task_creation_agent_kwargs (Dict, optional): Additional arguments
+ to pass to the task creation agent.
+ task_prioritization_agent_kwargs (Dict, optional): Additional
+ arguments to pass to the task prioritization agent.
+ output_language (str, optional): The language to be output by the
+ agents.
+ 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`)
+ """
+ self.assistant_agent = ChatAgent(
+ init_assistant_sys_msg,
+ output_language=output_language,
+ message_window_size=message_window_size,
+ **(assistant_agent_kwargs or {}),
+ )
+ self.assistant_sys_msg = self.assistant_agent.system_message
+ self.assistant_agent.reset()
+
+ self.task_creation_agent = TaskCreationAgent(
+ objective=self.specified_task_prompt,
+ role_name=self.assistant_sys_msg.role_name,
+ output_language=output_language,
+ message_window_size=message_window_size,
+ **(task_creation_agent_kwargs or {}),
+ )
+ self.task_creation_agent.reset()
+
+ self.task_prioritization_agent = TaskPrioritizationAgent(
+ objective=self.specified_task_prompt,
+ output_language=output_language,
+ message_window_size=message_window_size,
+ **(task_prioritization_agent_kwargs or {}),
+ )
+ self.task_prioritization_agent.reset()
+
+ def step(self) -> ChatAgentResponse:
+ r"""BabyAGI agent would pull the first task from the task list,
+ complete the task based on the context, then creates new tasks and
+ reprioritizes the task list based on the objective and the result of
+ the previous task. It returns assistant message.
+
+ Returns:
+ ChatAgentResponse: it contains the resulting assistant message,
+ whether the assistant agent terminated the conversation,
+ and any additional assistant information.
+
+ """
+ if not self.subtasks:
+ new_subtask_list = self.task_creation_agent.run(task_list=[])
+ prioritized_subtask_list = self.task_prioritization_agent.run(
+ new_subtask_list)
+ self.subtasks = deque(prioritized_subtask_list)
+
+ task_name = self.subtasks.popleft()
+ assistant_msg_msg = BaseMessage.make_user_message(
+ role_name=self.assistant_sys_msg.role_name, content=f"{task_name}")
+
+ assistant_response = self.assistant_agent.step(assistant_msg_msg)
+ assistant_msg = assistant_response.msgs[0]
+ self.assistant_agent.submit_message(assistant_msg)
+ self.task_creation_agent.submit_message(assistant_msg)
+ self.task_prioritization_agent.submit_message(assistant_msg)
+
+ self.solved_subtasks.append(task_name)
+ past_tasks = self.solved_subtasks + list(self.subtasks)
+
+ new_subtask_list = self.task_creation_agent.run(
+ task_list=past_tasks[-self.MAX_TASK_HISTORY:])
+
+ if new_subtask_list:
+ self.subtasks.extend(new_subtask_list)
+ prioritized_subtask_list = self.task_prioritization_agent.run(
+ task_list=list(self.subtasks)[-self.MAX_TASK_HISTORY:])
+ self.subtasks = deque(prioritized_subtask_list)
+ else:
+ print("no new tasks")
+ assistant_response.info['task_name'] = task_name
+ assistant_response.info['subtasks'] = list(self.subtasks)
+ if not self.subtasks:
+ terminated = True
+ assistant_response.info[
+ 'termination_reasons'] = "All tasks are solved"
+ return ChatAgentResponse([assistant_msg], terminated,
+ assistant_response.info)
+ return ChatAgentResponse([assistant_msg],
+ assistant_response.terminated,
+ assistant_response.info)
diff --git a/examples/ai_society/babyagi_playing.py b/examples/ai_society/babyagi_playing.py
new file mode 100644
index 000000000..976670d95
--- /dev/null
+++ b/examples/ai_society/babyagi_playing.py
@@ -0,0 +1,60 @@
+# =========== 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 BabyAGI
+from camel.utils import print_text_animated
+
+
+def main(model_type=None) -> None:
+
+ task_prompt = "Develop a trading bot for the stock market"
+ babyagi_session = BabyAGI(
+ assistant_role_name="Python Programmer",
+ assistant_agent_kwargs=dict(model=model_type),
+ user_role_name="Stock Trader",
+ task_prompt=task_prompt,
+ task_specify_agent_kwargs=dict(model=model_type),
+ message_window_size=5,
+ )
+
+ print(Fore.GREEN +
+ f"AI Assistant sys message:\n{babyagi_session.assistant_sys_msg}\n")
+
+ print(Fore.YELLOW + f"Original task prompt:\n{task_prompt}\n")
+ print(Fore.CYAN +
+ f"Specified task prompt:\n{babyagi_session.specified_task_prompt}\n")
+ print(Fore.RED +
+ f"Final task prompt:\n{babyagi_session.specified_task_prompt}\n")
+
+ chat_turn_limit, n = 15, 0
+ while n < chat_turn_limit:
+ n += 1
+ assistant_response = babyagi_session.step()
+ if assistant_response.terminated:
+ print(Fore.GREEN +
+ ("AI Assistant terminated. Reason: "
+ f"{assistant_response.info['termination_reasons']}."))
+ break
+ print_text_animated(Fore.RED + "Task Name:\n\n"
+ f"{assistant_response.info['task_name']}\n")
+ print_text_animated(Fore.GREEN + "AI Assistant:\n\n"
+ f"{assistant_response.msg.content}\n")
+ print_text_animated(Fore.BLUE + "Remaining Subtasks:\n\n"
+ f"{assistant_response.info['subtasks'][:5]}\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/test/test_babyagi_example.py b/examples/test/test_babyagi_example.py
new file mode 100644
index 000000000..8f4cb2c33
--- /dev/null
+++ b/examples/test/test_babyagi_example.py
@@ -0,0 +1,27 @@
+# =========== 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. ===========
+import pytest
+
+import examples.ai_society.babyagi_playing
+from camel.typing import ModelType
+
+parametrize = pytest.mark.parametrize('model', [
+ ModelType.STUB,
+ pytest.param(None, marks=pytest.mark.model_backend),
+])
+
+
+@parametrize
+def test_ai_society_babyagi_playing_example(model):
+ examples.ai_society.babyagi_playing.main(model_type=model)
diff --git a/test/agents/test_babyagi_playing.py b/test/agents/test_babyagi_playing.py
new file mode 100644
index 000000000..0285de5c5
--- /dev/null
+++ b/test/agents/test_babyagi_playing.py
@@ -0,0 +1,88 @@
+# =========== 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. ===========
+import pytest
+
+from camel.agents import ChatAgent, TaskCreationAgent, TaskPrioritizationAgent
+from camel.messages import BaseMessage
+from camel.societies import BabyAGI
+from camel.typing import ModelType, RoleType, TaskType
+
+parametrize = pytest.mark.parametrize('model', [
+ None,
+ pytest.param(ModelType.GPT_3_5_TURBO, marks=pytest.mark.model_backend),
+ pytest.param(ModelType.GPT_4, marks=pytest.mark.model_backend),
+])
+
+
+@parametrize
+def test_babyagi_playing_init(model: ModelType):
+
+ task_prompt = "Develop a trading bot for the stock market"
+
+ babyagi_playing = BabyAGI(
+ assistant_role_name="Python Programmer",
+ assistant_agent_kwargs=dict(model=model),
+ user_role_name="Stock Trader",
+ task_prompt=task_prompt,
+ task_specify_agent_kwargs=dict(model=model),
+ message_window_size=5,
+ )
+
+ assert babyagi_playing.task_type == TaskType.AI_SOCIETY
+ assert babyagi_playing.specified_task_prompt is not None
+
+ assert isinstance(babyagi_playing.assistant_sys_msg, BaseMessage)
+ assert babyagi_playing.assistant_sys_msg.role_type == RoleType.ASSISTANT
+
+ assert isinstance(babyagi_playing.assistant_agent, ChatAgent)
+ assert isinstance(babyagi_playing.task_creation_agent, TaskCreationAgent)
+ assert isinstance(babyagi_playing.task_prioritization_agent,
+ TaskPrioritizationAgent)
+
+ assert len(babyagi_playing.subtasks) == 0
+ assert len(babyagi_playing.solved_subtasks) == 0
+
+
+@parametrize
+def test_babyagi_playing_step(model: ModelType):
+ task_prompt = "Develop a trading bot for the stock market"
+
+ babyagi_playing = BabyAGI(
+ assistant_role_name="Python Programmer",
+ assistant_agent_kwargs=dict(model=model),
+ user_role_name="Stock Trader",
+ task_prompt=task_prompt,
+ task_specify_agent_kwargs=dict(model=model),
+ message_window_size=5,
+ )
+
+ print(f"AI Assistant sys message:\n{babyagi_playing.assistant_sys_msg}\n")
+ print(f"Original task prompt:\n{task_prompt}\n")
+ print(f"Specified task prompt:\n{babyagi_playing.specified_task_prompt}\n")
+
+ assistant_response = babyagi_playing.step()
+
+ assert isinstance(assistant_response.msgs, list)
+ assert len(assistant_response.msgs) == 1
+ assert isinstance(assistant_response.msgs[0], BaseMessage)
+ assert isinstance(assistant_response.terminated, bool)
+ assert assistant_response.terminated is False
+ assert isinstance(assistant_response.info, dict)
+
+ assert len(babyagi_playing.subtasks) > 0
+ assert len(babyagi_playing.solved_subtasks) == 1
+
+ assert len(babyagi_playing.assistant_agent.stored_messages) > 0
+ assert len(babyagi_playing.task_creation_agent.stored_messages) > 0
+ assert len(babyagi_playing.task_prioritization_agent.stored_messages) > 0
diff --git a/test/agents/test_task_agent.py b/test/agents/test_task_agent.py
index 5c689bc87..e6b6af67d 100644
--- a/test/agents/test_task_agent.py
+++ b/test/agents/test_task_agent.py
@@ -82,35 +82,10 @@ def test_task_planner_agent(model: Optional[ModelType]):
def test_task_creation_agent(model: Optional[ModelType]):
original_task_prompt = "Modeling molecular dynamics"
task_creation_agent = TaskCreationAgent(
- model_config=ChatGPTConfig(temperature=1.0), model=model,
- objective=original_task_prompt)
- task = "Search math tools for dynamics modeling"
- task_result = "Molecular dynamics trajectories are the result of \
- molecular dynamics simulations. Trajectories are sequential \
- snapshots of simulated molecular system which represents atomic \
- coordinates at specific time periods. Based on the definition, \
- in a text format trajectory files are characterized by their \
- simplicity and uselessness. To obtain information from such files, \
- special programs and information processing techniques are applied: \
- from molecular dynamics animation to finding characteristics \
- along the trajectory (versus time). In this review, we describe \
- different programs for processing molecular dynamics trajectories. \
- The performance of these programs, usefulness for analyses of \
- molecular dynamics trajectories, strongs and weaks are discussed."
-
- planned_task = task_creation_agent.run(
- previous_task=task,
- task_result=task_result,
- )
- print(f"Planned task list:\n{planned_task}\n")
-
- assert isinstance(planned_task, list)
+ role_name="PhD in molecular biology", objective=original_task_prompt,
+ model=model, model_config=ChatGPTConfig(temperature=1.0))
task_list = ["Study the computational technology for dynamics modeling"]
- planned_task = task_creation_agent.run(
- previous_task=task,
- task_result=task_result,
- task_list=task_list,
- )
+ planned_task = task_creation_agent.run(task_list=task_list, )
print(f"Planned task list:\n{planned_task}\n")
assert isinstance(planned_task, list)