File size: 11,855 Bytes
fcaa164 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 |
# ========= Copyright 2023-2024 @ 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-2024 @ 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.logger import get_logger
from camel.messages import BaseMessage
from camel.prompts import TextPrompt
from camel.types import RoleType, TaskType
logger = get_logger(__name__)
class BabyAGI:
r"""The BabyAGI Agent adapted from `"Task-driven Autonomous Agent"
<https://github.com/yoheinakajima/babyagi>`_.
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: Optional[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=getattr(self.assistant_sys_msg, 'role_name', None)
or "assistant",
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
re-prioritizes 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=getattr(self.assistant_sys_msg, 'role_name', None)
or "assistant",
content=f"{task_name}",
)
assistant_response = self.assistant_agent.step(assistant_msg_msg)
assistant_msg = assistant_response.msgs[0]
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:
logger.info("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(
msgs=[assistant_msg],
terminated=terminated,
info=assistant_response.info,
)
return ChatAgentResponse(
msgs=[assistant_msg],
terminated=assistant_response.terminated,
info=assistant_response.info,
)
|