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

Feat: workforce stable version (#877)

Isaac Jin5a87cb1d9ff2
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.py
index ce1e55884..9538c9712 100644
--- a/camel/agents/chat_agent.py
+++ b/camel/agents/chat_agent.py
@@ -622,9 +622,11 @@ class ChatAgent(BaseAgent):
# Replace the original tools with the structuring function
self.func_dict = {func.get_function_name(): func.func}
+ self.model_backend.model_config_dict = original_model_dict.copy()
self.model_backend.model_config_dict["tools"] = [
func.get_openai_tool_schema()
]
+ self.model_backend.model_config_dict["tool_choice"] = "required"
openai_messages, num_tokens = self.memory.get_context()
(
diff --git a/camel/tasks/task.py b/camel/tasks/task.py
index d118179c4..2521f5b0e 100644
--- a/camel/tasks/task.py
+++ b/camel/tasks/task.py
@@ -93,6 +93,10 @@ class Task(BaseModel):
result: Optional[str] = ""
+ failure_count: int = 0
+
+ additional_info: Optional[str] = None
+
@classmethod
def from_message(cls, message: BaseMessage) -> "Task":
r"""Create a task from a message.
@@ -193,7 +197,7 @@ class Task(BaseModel):
def decompose(
self,
agent: ChatAgent,
- template: TextPrompt = TASK_DECOMPOSE_PROMPT,
+ prompt: Optional[str] = None,
task_parser: Callable[[str, str], List["Task"]] = parse_response,
) -> List["Task"]:
r"""Decompose a task to a list of sub-tasks. It can be used for data
@@ -201,8 +205,8 @@ class Task(BaseModel):
Args:
agent (ChatAgent): An agent that used to decompose the task.
- template (TextPrompt): The prompt template to decompose
- task. If not provided, the default template will be used.
+ prompt (str, optional): A prompt to decompose the task. If not
+ provided, the default prompt will be used.
task_parser (Callable[[str, str], List[Task]], optional): A
function to extract Task from response. If not provided,
the default parse_response will be used.
@@ -212,7 +216,7 @@ class Task(BaseModel):
"""
role_name = agent.role_name
- content = template.format(
+ content = prompt or TASK_DECOMPOSE_PROMPT.format(
role_name=role_name,
content=self.content,
)
@@ -221,6 +225,8 @@ class Task(BaseModel):
)
response = agent.step(msg)
tasks = task_parser(response.msg.content, self.id)
+ for task in tasks:
+ task.additional_info = self.additional_info
return tasks
def compose(
@@ -248,6 +254,7 @@ class Task(BaseModel):
content = template.format(
role_name=role_name,
content=self.content,
+ additional_info=self.additional_info,
other_results=sub_tasks_result,
)
msg = BaseMessage.make_user_message(
diff --git a/camel/tasks/task_prompt.py b/camel/tasks/task_prompt.py
index 2b1b7c744..b6d43977f 100644
--- a/camel/tasks/task_prompt.py
+++ b/camel/tasks/task_prompt.py
@@ -39,6 +39,10 @@ The root task is:
{content}
+The additional information of the task is:
+
+{additional_info}
+
The related tasks result and status:
{other_results}
diff --git a/camel/utils/commons.py b/camel/utils/commons.py
index 62935d609..943e398c7 100644
--- a/camel/utils/commons.py
+++ b/camel/utils/commons.py
@@ -381,10 +381,17 @@ def json_to_function_code(json_obj: Dict) -> str:
docstring_args = []
return_keys = []
+ prop_to_python = {
+ 'string': 'str',
+ 'number': 'float',
+ 'integer': 'int',
+ 'boolean': 'bool',
+ }
+
for prop in required:
description = properties[prop]['description']
prop_type = properties[prop]['type']
- python_type = 'str' if prop_type == 'string' else prop_type
+ python_type = prop_to_python.get(prop_type, prop_type)
args.append(f"{prop}: {python_type}")
docstring_args.append(
f" {prop} ({python_type}): {description}."
diff --git a/camel/workforce/__init__.py b/camel/workforce/__init__.py
index 09c9b6d4d..8435f9e90 100644
--- a/camel/workforce/__init__.py
+++ b/camel/workforce/__init__.py
@@ -12,12 +12,12 @@
# limitations under the License.
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
-from .base import BaseNode
-from .manager_node import ManagerNode
-from .worker_node import WorkerNode
+from .role_playing_worker import RolePlayingWorker
+from .single_agent_worker import SingleAgentWorker
+from .workforce import Workforce
__all__ = [
- "BaseNode",
- "WorkerNode",
- "ManagerNode",
+ "Workforce",
+ "SingleAgentWorker",
+ "RolePlayingWorker",
]
diff --git a/camel/workforce/base.py b/camel/workforce/base.py
index 678f84e91..d28f9690f 100644
--- a/camel/workforce/base.py
+++ b/camel/workforce/base.py
@@ -15,36 +15,40 @@ from abc import ABC, abstractmethod
from typing import Any
from camel.workforce.task_channel import TaskChannel
+from camel.workforce.utils import check_if_running
class BaseNode(ABC):
def __init__(self, description: str) -> None:
self.node_id = str(id(self))
self.description = description
- # every node is initialized to use its own channel
self._channel: TaskChannel = TaskChannel()
self._running = False
+ @check_if_running(False)
def reset(self, *args: Any, **kwargs: Any) -> Any:
"""Resets the node to its initial state."""
- raise NotImplementedError()
+ self._channel = TaskChannel()
+ self._running = False
@abstractmethod
def set_channel(self, channel: TaskChannel):
r"""Sets the channel for the node."""
+ pass
@abstractmethod
async def _listen_to_channel(self):
r"""Listens to the channel and handle tasks. This method should be
the main loop for the node.
"""
+ pass
@abstractmethod
async def start(self):
r"""Start the node."""
+ pass
@abstractmethod
def stop(self):
- r"""
- Stop the node.
- """
+ r"""Stop the node."""
+ pass
diff --git a/camel/workforce/manager_node.py b/camel/workforce/manager_node.py
deleted file mode 100644
index d4a748ab2..000000000
--- a/camel/workforce/manager_node.py
+++ /dev/null
@@ -1,299 +0,0 @@
-# =========== 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 __future__ import annotations
-
-import asyncio
-from collections import deque
-from typing import Deque, Dict, List, Optional
-
-from colorama import Fore
-
-from camel.agents import ChatAgent
-from camel.messages.base import BaseMessage
-from camel.tasks.task import Task, TaskState
-from camel.workforce.base import BaseNode
-from camel.workforce.single_agent_node import SingleAgentNode
-from camel.workforce.task_channel import TaskChannel
-from camel.workforce.utils import (
- check_if_running,
- parse_assign_task_resp,
- parse_create_node_resp,
-)
-from camel.workforce.worker_node import WorkerNode
-from camel.workforce.workforce_prompt import (
- ASSIGN_TASK_PROMPT,
- CREATE_NODE_PROMPT,
-)
-
-
-class ManagerNode(BaseNode):
- r"""A node that manages multiple nodes. It will split the task it
- receives into subtasks and assign them to the child nodes under
- it, and also handles the situation when the task fails.
-
- Args:
- description (str): Description of the node.
- coordinator_agent_kwargs (Optional[Dict]): Keyword arguments for the
- coordinator agent, e.g. `model`, `api_key`, `tools`, etc.
- task_agent_kwargs (Optional[Dict]): Keyword arguments for the task
- agent, e.g. `model`, `api_key`, `tools`, etc.
- """
-
- def __init__(
- self,
- description: str,
- children: List[BaseNode],
- coordinator_agent_kwargs: Optional[Dict] = None,
- task_agent_kwargs: Optional[Dict] = None,
- ) -> None:
- super().__init__(description)
- self._child_listening_tasks: Deque[asyncio.Task] = deque()
- self._children = children
-
- coord_agent_sysmsg = BaseMessage.make_assistant_message(
- role_name="Workforce Manager",
- content="You are coordinating a group of workers. A worker can be "
- "a group of agents or a single agent. Each worker is created to"
- " solve a specific kind of task. Your job includes assigning "
- "tasks to a existing worker, creating a new worker for a task, "
- "etc.",
- )
- self.coordinator_agent = ChatAgent(
- coord_agent_sysmsg, **(coordinator_agent_kwargs or {})
- )
-
- task_sys_msg = BaseMessage.make_assistant_message(
- role_name="Task Planner",
- content="You are going to compose and decompose tasks.",
- )
- self.task_agent = ChatAgent(task_sys_msg, **(task_agent_kwargs or {}))
-
- # if there is one, will set by the workforce class wrapping this
- self._task: Optional[Task] = None
- self._pending_tasks: Deque[Task] = deque()
-
- @check_if_running(False)
- def set_main_task(self, task: Task) -> None:
- r"""Set the main task for the node."""
- self._task = task
-
- def _get_child_nodes_info(self) -> str:
- r"""Get the information of all the child nodes under this node."""
- return '\n'.join(
- f'{child.node_id}: {child.description}' for child in self._children
- )
-
- def _find_assignee(
- self,
- task: Task,
- failed_log: Optional[str] = None,
- ) -> str:
- r"""Assigns a task to a child node if capable, otherwise create a
- new worker node.
-
- Parameters:
- task (Task): The task to be assigned.
- failed_log (Optional[str]): Optional log of a previous failed
- attempt.
-
- Returns:
- str: ID of the assigned node.
- """
- prompt = ASSIGN_TASK_PROMPT.format(
- content=task.content,
- child_nodes_info=self._get_child_nodes_info(),
- )
- req = BaseMessage.make_user_message(
- role_name="User",
- content=prompt,
- )
- response = self.coordinator_agent.step(req)
- try:
- print(f"{Fore.YELLOW}{response.msg.content}{Fore.RESET}")
- assignee_id = parse_assign_task_resp(response.msg.content)
- except ValueError:
- assignee_id = self._create_worker_node_for_task(task).node_id
- return assignee_id
-
- async def _post_task(self, task: Task, assignee_id: str) -> None:
- await self._channel.post_task(task, self.node_id, assignee_id)
-
- async def _post_dependency(self, dependency: Task) -> None:
- await self._channel.post_dependency(dependency, self.node_id)
-
- def _create_worker_node_for_task(self, task: Task) -> WorkerNode:
- r"""Creates a new worker node for a given task and add it to the
- children list of this node. This is one of the actions that
- the coordinator can take when a task has failed.
-
- Args:
- task (Task): The task for which the worker node is created.
-
- Returns:
- WorkerNode: The created worker node.
- """
- prompt = CREATE_NODE_PROMPT.format(
- content=task.content,
- child_nodes_info=self._get_child_nodes_info(),
- )
- req = BaseMessage.make_user_message(
- role_name="User",
- content=prompt,
- )
- response = self.coordinator_agent.step(req)
- new_node_conf = parse_create_node_resp(response.msg.content)
-
- worker_sysmsg = BaseMessage.make_assistant_message(
- role_name=new_node_conf.role,
- content=new_node_conf.system,
- )
-
- # TODO: add a default selection of tools for the worker
- worker = ChatAgent(worker_sysmsg)
-
- new_node = SingleAgentNode(
- description=new_node_conf.description,
- worker=worker,
- )
- new_node.set_channel(self._channel)
-
- print(
- f"{Fore.GREEN}New worker node {new_node.node_id} created."
- f"{Fore.RESET}"
- )
-
- self._children.append(new_node)
- self._child_listening_tasks.append(
- asyncio.create_task(new_node.start())
- )
- return new_node
-
- async def _get_returned_task(self) -> Task:
- r"""Get the task that's published by this node and just get returned
- from the assignee.
- """
- return await self._channel.get_returned_task_by_publisher(self.node_id)
-
- async def _post_ready_tasks(self) -> None:
- r"""Send all the pending tasks that have all the dependencies met to
- the channel, or directly return if there is none. For now, we will
- directly send the first task in the pending list because all the tasks
- are linearly dependent."""
-
- if not self._pending_tasks:
- return
-
- ready_task = self._pending_tasks[0]
-
- # if the task has failed previously, just compose and send the task
- # to the channel as a dependency
- if ready_task.state == TaskState.FAILED:
- # TODO: the composing of tasks seems not work very well
- ready_task.compose(self.task_agent)
- # remove the subtasks from the channel
- for subtask in ready_task.subtasks:
- await self._channel.remove_task(subtask.id)
- # send the task to the channel as a dependency
- await self._post_dependency(ready_task)
- self._pending_tasks.popleft()
- # try to send the next task in the pending list
- await self._post_ready_tasks()
- else:
- # directly post the task to the channel if it's a new one
- # find a node to assign the task
- assignee_id = self._find_assignee(task=ready_task)
- await self._post_task(ready_task, assignee_id)
-
- async def _handle_failed_task(self, task: Task) -> None:
- # remove the failed task from the channel
- await self._channel.remove_task(task.id)
- if task.get_depth() >= 3:
- # create a new WF and reassign
- # TODO: add a state for reassign?
- assignee = self._create_worker_node_for_task(task)
- # print('create_new_assignee:', assignee)
- await self._post_task(task, assignee.node_id)
- else:
- subtasks = task.decompose(self.task_agent)
- # Insert packets at the head of the queue
- self._pending_tasks.extendleft(reversed(subtasks))
- await self._post_ready_tasks()
-
- async def _handle_completed_task(self, task: Task) -> None:
- # archive the packet, making it into a dependency
- self._pending_tasks.popleft()
- await self._channel.archive_task(task.id)
- await self._post_ready_tasks()
-
- @check_if_running(False)
- def set_channel(self, channel: TaskChannel):
- r"""Set the channel for the node and all the child nodes under it."""
- self._channel = channel
- for child in self._children:
- child.set_channel(channel)
-
- @check_if_running(False)
- async def _listen_to_channel(self) -> None:
- r"""Continuously listen to the channel, post task to the channel and
- track the status of posted tasks.
- """
-
- self._running = True
- print(f"{Fore.GREEN}Manager node {self.node_id} started.{Fore.RESET}")
-
- # if this node is at the top level, it will have an initial task
- # the initial task must be decomposed into subtasks first
- if self._task is not None:
- subtasks = self._task.decompose(self.task_agent)
- self._pending_tasks.extend(subtasks)
- self._task.state = TaskState.FAILED
- self._pending_tasks.append(self._task)
-
- # before starting the loop, send ready pending tasks to the channel
- await self._post_ready_tasks()
-
- await self._channel.print_channel()
-
- while self._task is None or self._pending_tasks:
- returned_task = await self._get_returned_task()
- if returned_task.state == TaskState.DONE:
- await self._handle_completed_task(returned_task)
- elif returned_task.state == TaskState.FAILED:
- await self._handle_failed_task(returned_task)
- else:
- raise ValueError(
- f"Task {returned_task.id} has an unexpected state."
- )
-
- # shut down the whole workforce tree
- self.stop()
-
- @check_if_running(False)
- async def start(self) -> None:
- r"""Start itself and all the child nodes under it."""
- for child in self._children:
- child_listening_task = asyncio.create_task(child.start())
- self._child_listening_tasks.append(child_listening_task)
- await self._listen_to_channel()
-
- @check_if_running(True)
- def stop(self) -> None:
- r"""Stop all the child nodes under it. The node itself will be stopped
- by its parent node.
- """
- for child in self._children:
- child.stop()
- for child_task in self._child_listening_tasks:
- child_task.cancel()
- self._running = False
diff --git a/camel/workforce/prompts.py b/camel/workforce/prompts.py
new file mode 100644
index 000000000..260f94a31
--- /dev/null
+++ b/camel/workforce/prompts.py
@@ -0,0 +1,175 @@
+# =========== 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 camel.prompts import TextPrompt
+
+# ruff: noqa: E501
+CREATE_NODE_PROMPT = TextPrompt(
+ """You need to use the given information to create a new worker node that contains a single agent for solving the category of tasks of the given one.
+The content of the given task is:
+
+==============================
+{content}
+==============================
+
+Here are some additional information about the task:
+
+==============================
+{additional_info}
+==============================
+
+Following is the information of the existing worker nodes. The format is <ID>:<description>:<additional_info>.
+
+==============================
+{child_nodes_info}
+==============================
+
+You must return the following information:
+1. The role of the agent working in the worker node, e.g. "programmer", "researcher", "product owner".
+2. The system message that will be sent to the agent in the node.
+3. The description of the new worker node itself.
+
+You should ensure that the node created is capable of solving all the tasks in the same category as the given one, don't make it too specific.
+Also, there should be no big overlap between the new work node and the existing ones.
+The information returned should be concise and clear.
+"""
+)
+
+ASSIGN_TASK_PROMPT = TextPrompt(
+ """You need to assign the task to a worker node.
+The content of the task is:
+
+==============================
+{content}
+==============================
+
+Here are some additional information about the task:
+
+==============================
+{additional_info}
+==============================
+
+Following is the information of the existing worker nodes. The format is <ID>:<description>:<additional_info>.
+
+==============================
+{child_nodes_info}
+==============================
+
+You must return the ID of the worker node that you think is most capable of doing the task.
+"""
+)
+
+PROCESS_TASK_PROMPT = TextPrompt(
+ """You need to process one given task.
+Here are results of some prerequisite tasks that you can refer to:
+
+==============================
+{dependency_tasks_info}
+==============================
+
+The content of the task that you need to do is:
+
+==============================
+{content}
+==============================
+
+Here are some additional information about the task:
+
+==============================
+{additional_info}
+==============================
+
+You are asked to return the result of the given task.
+However, if you think you can't finish the task, you MUST set the fail flag and leave the result empty.
+"""
+)
+
+
+ROLEPLAY_PROCESS_TASK_PROMPT = TextPrompt(
+ """You need to process the task. It is recommended that tools be actively called when needed.
+Here are results of some prerequisite tasks that you can refer to:
+
+==============================
+{dependency_task_info}
+==============================
+
+The content of the task that you need to do is:
+
+==============================
+{content}
+==============================
+
+Here are some additional information about the task:
+
+==============================
+{additional_info}
+==============================
+
+You must return the result of the given task.
+"""
+)
+
+ROLEPLAY_SUMMARIZE_PROMPT = TextPrompt(
+ """For this scenario, the roles of the user is {user_role} and role of the assistant is {assistant_role}.
+Here is the content of the task they are trying to solve:
+
+==============================
+{task_content}
+==============================
+
+Here are some additional information about the task:
+
+==============================
+{additional_info}
+==============================
+
+Here is their chat history on the task:
+
+==============================
+{chat_history}
+==============================
+
+Now you should summarize the scenario and return the result of the task.
+However, if you think they didn't finish the task, you MUST set the fail flag and leave the result empty.
+"""
+)
+
+WF_TASK_DECOMPOSE_PROMPT = r"""You need to split the given task into
+subtasks according to the workers available in the group.
+The content of the task is:
+
+==============================
+{content}
+==============================
+
+There are some additional information about the task:
+
+==============================
+{additional_info}
+==============================
+
+Following are the available workers, given in the format <ID>: <description>.
+
+==============================
+{child_nodes_info}
+==============================
+
+You must return the subtasks in the format of a numbered list within <tasks> tags, as shown below:
+
+<tasks>
+<task>Subtask 1</task>
+<task>Subtask 2</task>
+</tasks>
+
+Though it's not a must, you should try your best effort to make each subtask achievable for a worker. The tasks should be clear and concise.
+"""
diff --git a/camel/workforce/role_playing_node.py b/camel/workforce/role_playing_node.py
deleted file mode 100644
index e34e46234..000000000
--- a/camel/workforce/role_playing_node.py
+++ /dev/null
@@ -1,168 +0,0 @@
-# =========== 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 __future__ import annotations
-
-from typing import Dict, List, Optional
-
-from colorama import Fore, Style
-
-from camel.agents.chat_agent import ChatAgent, FunctionCallingRecord
-from camel.messages.base import BaseMessage
-from camel.societies import RolePlaying
-from camel.tasks.task import Task, TaskState
-from camel.utils import print_text_animated
-from camel.workforce.utils import parse_task_result_resp
-from camel.workforce.worker_node import WorkerNode
-from camel.workforce.workforce_prompt import (
- ROLEPLAY_PROCESS_TASK_PROMPT,
- ROLEPLAY_SUMMERIZE_PROMPT,
-)
-
-
-class RolePlayingNode(WorkerNode):
- r"""A worker node that contains a role playing.
-
- Args:
- description (str): Description of the node.
- assistant_role_name (str): The role name of the assistant agent.
- user_role_name (str): The role name of the user agent.
- assistant_agent_kwargs (Optional[Dict], optional): The keyword
- arguments to initialize the assistant agent in the role playing,
- like the model name, etc. Defaults to None.
- user_agent_kwargs (Optional[Dict], optional): The keyword arguments to
- initialize the user agent in the role playing, like the model name,
- etc. Defaults to None.
- chat_turn_limit (int, optional): The maximum number of chat turns in
- the role playing. Defaults to 3.
- """
-
- def __init__(
- self,
- description: str,
- assistant_role_name: str,
- user_role_name: str,
- assistant_agent_kwargs: Optional[Dict] = None,
- user_agent_kwargs: Optional[Dict] = None,
- chat_turn_limit: int = 3,
- ) -> None:
- super().__init__(description)
- sys_message = BaseMessage.make_assistant_message(
- role_name="Summarizer",
- content="Good at summarizing the results of the chat logs",
- )
- self.summerize_agent = ChatAgent(sys_message)
- self.chat_turn_limit = chat_turn_limit
- self.assistant_role_name = assistant_role_name
- self.user_role_name = user_role_name
- self.assistant_agent_kwargs = assistant_agent_kwargs
- self.user_agent_kwargs = user_agent_kwargs
-
- async def _process_task(
- self, task: Task, dependencies: List[Task]
- ) -> TaskState:
- r"""Processes a task leveraging its dependencies through role-playing.
-
- This method orchestrates a role-playing session between an AI
- assistant and an AI user to process a given task. It initiates with a
- generated prompt based on the task and its dependencies, conducts a
- dialogue up to a specified chat turn limit, and then summarizes the
- dialogue to determine the task's outcome.
-
- Args:
- task (Task): The task object to be processed, containing necessary
- details like content and type.
- dependencies (List[Task]): A list of task objects that the current
- task depends on.
-
- Returns:
- TaskState: `TaskState.DONE` if processed successfully, otherwise
- `TaskState.FAILED`.
- """
- try:
- dependency_tasks_info = self._get_dep_tasks_info(dependencies)
- prompt = ROLEPLAY_PROCESS_TASK_PROMPT.format(
- content=task.content,
- type=task.type,
- dependency_task_info=dependency_tasks_info,
- )
- role_play_session = RolePlaying(
- assistant_role_name=self.assistant_role_name,
- user_role_name=self.user_role_name,
- assistant_agent_kwargs=self.assistant_agent_kwargs,
- user_agent_kwargs=self.user_agent_kwargs,
- task_prompt=prompt,
- with_task_specify=False,
- )
- n = 0
- input_msg = role_play_session.init_chat()
- chat_history = []
- while n < self.chat_turn_limit:
- n += 1
- assistant_response, user_response = role_play_session.step(
- input_msg
- )
-
- if assistant_response.terminated:
- reason = assistant_response.info['termination_reasons']
- print(
- Fore.GREEN + f"AI Assistant terminated. Reason: "
- f"{reason}. "
- )
- break
- if user_response.terminated:
- reason = user_response.info['termination_reasons']
- print(
- Fore.GREEN + f"AI User terminated. Reason: {reason}."
- )
- break
- print_text_animated(
- Fore.BLUE + f"AI User:\n\n{user_response.msg.content}\n",
- delay=0.005,
- )
- chat_history.append(f"AI User: {user_response.msg.content}")
-
- print_text_animated(Fore.GREEN + "AI Assistant:", delay=0.005)
- tool_calls: List[FunctionCallingRecord] = (
- assistant_response.info['tool_calls']
- )
- for func_record in tool_calls:
- print_text_animated(f"{func_record}", delay=0.005)
- print_text_animated(
- f"{assistant_response.msg.content}\n", delay=0.005
- )
- chat_history.append(
- f"AI Assistant: {assistant_response.msg.content}"
- )
-
- if "CAMEL_TASK_DONE" in user_response.msg.content:
- break
-
- input_msg = assistant_response.msg
-
- chat_history_str = "\n".join(chat_history)
- prompt = ROLEPLAY_SUMMERIZE_PROMPT.format(
- content=task.content,
- type=task.type,
- chat_history=chat_history_str,
- )
- req = BaseMessage.make_user_message(
- role_name="User",
- content=prompt,
- )
- response = self.summerize_agent.step(req)
- task.result = parse_task_result_resp(response.msg.content)
- print(Style.RESET_ALL + 'Task result:', task.result, '\n')
- return TaskState.DONE
- except Exception:
- return TaskState.FAILED
diff --git a/camel/workforce/role_playing_worker.py b/camel/workforce/role_playing_worker.py
new file mode 100644
index 000000000..71d2d4706
--- /dev/null
+++ b/camel/workforce/role_playing_worker.py
@@ -0,0 +1,181 @@
+# =========== 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 __future__ import annotations
+
+import ast
+from typing import Dict, List, Optional
+
+from colorama import Fore
+
+from camel.agents.chat_agent import ChatAgent
+from camel.messages.base import BaseMessage
+from camel.societies import RolePlaying
+from camel.tasks.task import Task, TaskState
+from camel.utils import print_text_animated
+from camel.workforce.prompts import (
+ ROLEPLAY_PROCESS_TASK_PROMPT,
+ ROLEPLAY_SUMMARIZE_PROMPT,
+)
+from camel.workforce.utils import TaskResult
+from camel.workforce.worker import Worker
+
+
+class RolePlayingWorker(Worker):
+ r"""A worker node that contains a role playing.
+
+ Args:
+ description (str): Description of the node.
+ assistant_role_name (str): The role name of the assistant agent.
+ user_role_name (str): The role name of the user agent.
+ assistant_agent_kwargs (Optional[Dict], optional): The keyword
+ arguments to initialize the assistant agent in the role playing,
+ like the model name, etc. Defaults to None.
+ user_agent_kwargs (Optional[Dict], optional): The keyword arguments to
+ initialize the user agent in the role playing, like the model name,
+ etc. Defaults to None.
+ chat_turn_limit (int, optional): The maximum number of chat turns in
+ the role playing. Defaults to 3.
+ """
+
+ def __init__(
+ self,
+ description: str,
+ assistant_role_name: str,
+ user_role_name: str,
+ assistant_agent_kwargs: Optional[Dict] = None,
+ user_agent_kwargs: Optional[Dict] = None,
+ chat_turn_limit: int = 3,
+ ) -> None:
+ super().__init__(description)
+ summ_sys_msg = BaseMessage.make_assistant_message(
+ role_name="Summarizer",
+ content="You are a good summarizer. You will be presented with "
+ "scenarios where an assistant and a user with specific roles "
+ "are trying to solve a task. Your job is summarizing the result "
+ "of the task based on the chat history.",
+ )
+ self.summarize_agent = ChatAgent(summ_sys_msg)
+ self.chat_turn_limit = chat_turn_limit
+ self.assistant_role_name = assistant_role_name
+ self.user_role_name = user_role_name
+ self.assistant_agent_kwargs = assistant_agent_kwargs
+ self.user_agent_kwargs = user_agent_kwargs
+
+ async def _process_task(
+ self, task: Task, dependencies: List[Task]
+ ) -> TaskState:
+ r"""Processes a task leveraging its dependencies through role-playing.
+
+ This method orchestrates a role-playing session between an AI
+ assistant and an AI user to process a given task. It initiates with a
+ generated prompt based on the task and its dependencies, conducts a
+ dialogue up to a specified chat turn limit, and then summarizes the
+ dialogue to determine the task's outcome.
+
+ Args:
+ task (Task): The task object to be processed, containing necessary
+ details like content and type.
+ dependencies (List[Task]): A list of task objects that the current
+ task depends on.
+
+ Returns:
+ TaskState: `TaskState.DONE` if processed successfully, otherwise
+ `TaskState.FAILED`.
+ """
+ dependency_tasks_info = self._get_dep_tasks_info(dependencies)
+ prompt = ROLEPLAY_PROCESS_TASK_PROMPT.format(
+ content=task.content,
+ dependency_task_info=dependency_tasks_info,
+ additional_info=task.additional_info,
+ )
+ role_play_session = RolePlaying(
+ assistant_role_name=self.assistant_role_name,
+ user_role_name=self.user_role_name,
+ assistant_agent_kwargs=self.assistant_agent_kwargs,
+ user_agent_kwargs=self.user_agent_kwargs,
+ task_prompt=prompt,
+ with_task_specify=False,
+ )
+ n = 0
+ input_msg = role_play_session.init_chat()
+ chat_history = []
+ while n < self.chat_turn_limit:
+ n += 1
+ assistant_response, user_response = role_play_session.step(
+ input_msg
+ )
+
+ if assistant_response.terminated:
+ reason = assistant_response.info['termination_reasons']
+ print(
+ f"{Fore.GREEN}AI Assistant terminated. Reason: "
+ f"{reason}.{Fore.RESET}"
+ )
+ break
+
+ if user_response.terminated:
+ reason = user_response.info['termination_reasons']
+ print(
+ f"{Fore.GREEN}AI User terminated. Reason: {reason}."
+ f"{Fore.RESET}"
+ )
+ break
+
+ print_text_animated(
+ f"{Fore.BLUE}AI User:\n\n{user_response.msg.content}"
+ f"{Fore.RESET}\n",
+ delay=0.005,
+ )
+ chat_history.append(f"AI User: {user_response.msg.content}")
+
+ print_text_animated(
+ f"{Fore.GREEN}AI Assistant:{Fore.RESET}", delay=0.005
+ )
+
+ for func_record in assistant_response.info['tool_calls']:
+ print(func_record)
+
+ print_text_animated(
+ f"\n{Fore.GREEN}{assistant_response.msg.content}"
+ f"{Fore.RESET}\n",
+ delay=0.005,
+ )
+ chat_history.append(
+ f"AI Assistant: {assistant_response.msg.content}"
+ )
+
+ if "CAMEL_TASK_DONE" in user_response.msg.content:
+ break
+
+ input_msg = assistant_response.msg
+
+ chat_history_str = "\n".join(chat_history)
+ prompt = ROLEPLAY_SUMMARIZE_PROMPT.format(
+ user_role=self.user_role_name,
+ assistant_role=self.assistant_role_name,
+ content=task.content,
+ chat_history=chat_history_str,
+ additional_info=task.additional_info,
+ )
+ req = BaseMessage.make_user_message(
+ role_name="User",
+ content=prompt,
+ )
+ response = self.summarize_agent.step(req, output_schema=TaskResult)
+ result_dict = ast.literal_eval(response.msg.content)
+ task_result = TaskResult(**result_dict)
+ task.result = task_result.content
+
+ print(f"Task result: {task.result}\n")
+ return TaskState.DONE
diff --git a/camel/workforce/single_agent_node.py b/camel/workforce/single_agent_worker.py
similarity index 52%
rename from camel/workforce/single_agent_node.py
rename to camel/workforce/single_agent_worker.py
index e3f603e6c..5a0c9cf2d 100644
--- a/camel/workforce/single_agent_node.py
+++ b/camel/workforce/single_agent_worker.py
@@ -13,32 +13,41 @@
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
from __future__ import annotations
-from typing import List
+import ast
+from typing import Any, List
-from camel.agents.base import BaseAgent
+from colorama import Fore
+
+from camel.agents import ChatAgent
from camel.messages.base import BaseMessage
from camel.tasks.task import Task, TaskState
-from camel.workforce.utils import parse_task_result_resp
-from camel.workforce.worker_node import WorkerNode
-from camel.workforce.workforce_prompt import PROCESS_TASK_PROMPT
+from camel.utils import print_text_animated
+from camel.workforce.prompts import PROCESS_TASK_PROMPT
+from camel.workforce.utils import TaskResult
+from camel.workforce.worker import Worker
-class SingleAgentNode(WorkerNode):
+class SingleAgentWorker(Worker):
r"""A worker node that consists of a single agent.
Args:
description (str): Description of the node.
- worker (BaseAgent): Worker of the node. A single agent.
+ worker (ChatAgent): Worker of the node. A single agent.
"""
def __init__(
self,
description: str,
- worker: BaseAgent,
+ worker: ChatAgent,
) -> None:
super().__init__(description)
self.worker = worker
+ def reset(self) -> Any:
+ r"""Resets the worker to its initial state."""
+ super().reset()
+ self.worker.reset()
+
async def _process_task(
self, task: Task, dependencies: List[Task]
) -> TaskState:
@@ -57,21 +66,39 @@ class SingleAgentNode(WorkerNode):
TaskState: `TaskState.DONE` if processed successfully, otherwise
`TaskState.FAILED`.
"""
+ dependency_tasks_info = self._get_dep_tasks_info(dependencies)
+ prompt = PROCESS_TASK_PROMPT.format(
+ content=task.content,
+ dependency_tasks_info=dependency_tasks_info,
+ additional_info=task.additional_info,
+ )
+ req = BaseMessage.make_user_message(
+ role_name="User",
+ content=prompt,
+ )
try:
- dependency_tasks_info = self._get_dep_tasks_info(dependencies)
- prompt = PROCESS_TASK_PROMPT.format(
- content=task.content,
- type=task.type,
- dependency_task_info=dependency_tasks_info,
+ response = self.worker.step(req, output_schema=TaskResult)
+ except Exception as e:
+ print(
+ f"{Fore.RED}Error occurred while processing task {task.id}:"
+ f"\n{e}{Fore.RESET}"
)
- req = BaseMessage.make_user_message(
- role_name="User",
- content=prompt,
+ return TaskState.FAILED
+
+ print(f"======\n{Fore.GREEN}Reply from {self}:{Fore.RESET}")
+
+ result_dict = ast.literal_eval(response.msg.content)
+ task_result = TaskResult(**result_dict)
+
+ if task_result.failed:
+ print(
+ f"{Fore.RED}{self} failed to process task {task.id}.\n======"
)
- response = self.worker.step(req)
- # print("info['tool_calls']:", response.info['tool_calls'])
- task.result = parse_task_result_resp(response.msg.content)
- print('Task result:', task.result, '\n')
- return TaskState.DONE
- except Exception:
return TaskState.FAILED
+
+ task.result = task_result.content
+ print_text_animated(
+ f'\n{Fore.GREEN}{task.result}{Fore.RESET}\n======',
+ delay=0.005,
+ )
+ return TaskState.DONE
diff --git a/camel/workforce/task_channel.py b/camel/workforce/task_channel.py
index c68ae556e..cc371172b 100644
--- a/camel/workforce/task_channel.py
+++ b/camel/workforce/task_channel.py
@@ -61,7 +61,7 @@ class Packet:
publisher_id: str,
assignee_id: Optional[str] = None,
status: PacketStatus = PacketStatus.SENT,
- ):
+ ) -> None:
self.task = task
self.publisher_id = publisher_id
self.assignee_id = assignee_id
@@ -83,7 +83,6 @@ class TaskChannel:
self._task_dict: Dict[str, Packet] = {}
async def get_returned_task_by_publisher(self, publisher_id: str) -> Task:
- await self.print_channel()
async with self._condition:
while True:
for task_id in self._task_id_list:
@@ -167,7 +166,6 @@ class TaskChannel:
raise ValueError(f"Task {task_id} not found.")
return self._task_dict[task_id].task
- async def print_channel(self):
+ async def get_channel_debug_info(self) -> str:
async with self._condition:
- print(self._task_dict)
- print(self._task_id_list)
+ return str(self._task_dict) + '\n' + str(self._task_id_list)
diff --git a/camel/workforce/utils.py b/camel/workforce/utils.py
index 5b9d4ffbb..e2148812a 100644
--- a/camel/workforce/utils.py
+++ b/camel/workforce/utils.py
@@ -11,66 +11,36 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
-import re
from functools import wraps
from typing import Callable
+from pydantic import BaseModel, Field
-class NodeConf:
- def __init__(self, role: str, system: str, description: str):
- self.role = role
- self.system = system
- self.description = description
-
-# TODO: integrate structured response directly instead of parsing
-def parse_create_node_resp(response: str) -> NodeConf:
- r"""Parses the response of the new workforce creation from the manager
- agent."""
- config = re.search(r"(<workforce>.*</workforce>)", response, re.DOTALL)
- if config is None:
- raise ValueError("No workforce configuration found in the response.")
- config_raw = config.group(1)
-
- try:
- import xml.etree.ElementTree as ET
-
- root = ET.fromstring(config_raw)
- workforce_info = {child.tag: child.text for child in root}
- except Exception as e:
- raise ValueError(f"Failed to parse workforce configuration: {e}")
-
- if (
- "role" not in workforce_info
- or "system" not in workforce_info
- or "description" not in workforce_info
- ):
- raise ValueError("Missing required fields in workforce configuration.")
-
- return NodeConf(
- role=workforce_info["role"] or "",
- system=workforce_info["system"] or "",
- description=workforce_info["description"] or "",
+class WorkerConf(BaseModel):
+ role: str = Field(
+ description="The role of the agent working in the work node."
+ )
+ sys_msg: str = Field(
+ description="The system message that will be sent to the agent in "
+ "the node."
+ )
+ description: str = Field(
+ description="The description of the new work node itself."
)
-def parse_assign_task_resp(response: str) -> str:
- r"""Parses the response of the task assignment from the manager agent."""
- assignee_id = re.search(r"<id>(.*)</id>", response)
- if assignee_id is None:
- raise ValueError("No assignee found in the response.")
- return assignee_id.group(1)
+class TaskResult(BaseModel):
+ content: str = Field(description="The result of the task.")
+ failed: bool = Field(
+ description="Flag indicating whether the task processing failed."
+ )
-def parse_task_result_resp(response: str) -> str:
- r"""Parses the result of the task from the signle agent workforce."""
- task_result = re.search(r"<result>(.*)</result>", response, re.DOTALL)
- failed_tag = re.search(r"<failed></failed>", response)
- if failed_tag:
- task_result = None
- if task_result is None:
- raise ValueError("No result found in the response.")
- return task_result.group(1)
+class TaskAssignResult(BaseModel):
+ assignee_id: str = Field(
+ description="The ID of the workforce that is assigned to the task."
+ )
def check_if_running(running: bool) -> Callable:
diff --git a/camel/workforce/worker_node.py b/camel/workforce/worker.py
similarity index 85%
rename from camel/workforce/worker_node.py
rename to camel/workforce/worker.py
index a651a813c..13d7d954e 100644
--- a/camel/workforce/worker_node.py
+++ b/camel/workforce/worker.py
@@ -13,6 +13,7 @@
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
from __future__ import annotations
+import logging
from abc import ABC, abstractmethod
from typing import List
@@ -23,8 +24,10 @@ from camel.workforce.base import BaseNode
from camel.workforce.task_channel import TaskChannel
from camel.workforce.utils import check_if_running
+logger = logging.getLogger(__name__)
-class WorkerNode(BaseNode, ABC):
+
+class Worker(BaseNode, ABC):
r"""A worker node that works on tasks. It is the basic unit of task
processing in the workforce system.
@@ -33,15 +36,15 @@ class WorkerNode(BaseNode, ABC):
"""
- # TODO: Make RolePlaying and Agent scceed from one parent class, so that
- # we don't need two different classes for the worker node.
-
def __init__(
self,
description: str,
) -> None:
super().__init__(description)
+ def __repr__(self):
+ return f"Worker node {self.node_id} ({self.description})"
+
@abstractmethod
async def _process_task(
self, task: Task, dependencies: List[Task]
@@ -52,6 +55,7 @@ class WorkerNode(BaseNode, ABC):
'DONE' if the task is successfully processed,
'FAILED' if the processing fails.
"""
+ pass
async def _get_assigned_task(self) -> Task:
r"""Get the task assigned to this node from the channel."""
@@ -80,27 +84,26 @@ class WorkerNode(BaseNode, ABC):
indefinitely.
"""
self._running = True
- print(f"{Fore.GREEN}Worker node {self.node_id} started.{Fore.RESET}")
+ logger.info(f"{self} started.")
while True:
- # get the earliest task assigned to this node
+ # Get the earliest task assigned to this node
task = await self._get_assigned_task()
print(
- f'worker node {self.node_id} get task:',
- task.id,
- task.content,
+ f"{Fore.YELLOW}{self} get task {task.id}: {task.content}"
+ f"{Fore.RESET}"
)
- # get the Task instance of dependencies
+ # Get the Task instance of dependencies
dependency_ids = await self._channel.get_dependency_ids()
task_dependencies = [
await self._channel.get_task_by_id(dep_id)
for dep_id in dependency_ids
]
- # process the task
+ # Process the task
task_state = await self._process_task(task, task_dependencies)
- # update the result and status of the task
+ # Update the result and status of the task
task.set_state(task_state)
await self._channel.return_task(task.id)
diff --git a/camel/workforce/workforce.py b/camel/workforce/workforce.py
index ae2d74a8d..9d4628919 100644
--- a/camel/workforce/workforce.py
+++ b/camel/workforce/workforce.py
@@ -11,39 +11,476 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
+from __future__ import annotations
+
+import ast
import asyncio
+import logging
+from collections import deque
+from typing import Deque, Dict, List, Optional
+
+from colorama import Fore
-from camel.tasks import Task
-from camel.workforce.manager_node import ManagerNode
+from camel.agents import ChatAgent
+from camel.configs import ChatGPTConfig
+from camel.messages.base import BaseMessage
+from camel.models import ModelFactory
+from camel.tasks.task import Task, TaskState
+from camel.toolkits import SEARCH_FUNCS, WEATHER_FUNCS, GoogleMapsToolkit
+from camel.types import ModelPlatformType, ModelType
+from camel.workforce.base import BaseNode
+from camel.workforce.prompts import (
+ ASSIGN_TASK_PROMPT,
+ CREATE_NODE_PROMPT,
+ WF_TASK_DECOMPOSE_PROMPT,
+)
+from camel.workforce.role_playing_worker import RolePlayingWorker
+from camel.workforce.single_agent_worker import SingleAgentWorker
from camel.workforce.task_channel import TaskChannel
+from camel.workforce.utils import (
+ TaskAssignResult,
+ WorkerConf,
+ check_if_running,
+)
+from camel.workforce.worker import Worker
+logger = logging.getLogger(__name__)
-class Workforce:
- r"""A class representing a workforce system.
+
+class Workforce(BaseNode):
+ r"""A system where multiple workder nodes (agents) cooperate together
+ to solve tasks. It can assign tasks to workder nodes and also take
+ strategies such as create new worker, decompose tasks, etc. to handle
+ situations when the task fails.
Args:
- name (str, optional): The name of the workforce system. Defaults to
- `"CAMEL Workforce"`.
- description (str, optional): A description of the workforce system.
- Defaults to `"A workforce system for managing tasks."`.
+ description (str): Description of the node.
+ children (Optional[List[BaseNode]], optional): List of child nodes
+ under this node. Each child node can be a worker node or
+ another workforce node. (default: :obj:`None`)
+ coordinator_agent_kwargs (Optional[Dict], optional): Keyword
+ arguments for the coordinator agent, e.g. `model`, `api_key`,
+ `tools`, etc. (default: :obj:`None`)
+ task_agent_kwargs (Optional[Dict], optional): Keyword arguments for
+ the task agent, e.g. `model`, `api_key`, `tools`, etc.
+ (default: :obj:`None`)
+ new_worker_agent_kwargs (Optional[Dict]): Default keyword arguments
+ for the worker agent that will be created during runtime to
+ handle failed tasks, e.g. `model`, `api_key`, `tools`, etc.
+ (default: :obj:`None`)
"""
def __init__(
self,
- root_node: ManagerNode,
- name: str = "CAMEL Workforce",
- description: str = "A workforce system for managing tasks.",
+ description: str,
+ children: Optional[List[BaseNode]] = None,
+ coordinator_agent_kwargs: Optional[Dict] = None,
+ task_agent_kwargs: Optional[Dict] = None,
+ new_worker_agent_kwargs: Optional[Dict] = None,
) -> None:
- self.name = name
- self.description = description
- self._root_node = root_node
+ super().__init__(description)
+ self._child_listening_tasks: Deque[asyncio.Task] = deque()
+ self._children = children or []
+ self.new_worker_agent_kwargs = new_worker_agent_kwargs
+
+ coord_agent_sys_msg = BaseMessage.make_assistant_message(
+ role_name="Workforce Manager",
+ content="You are coordinating a group of workers. A worker can be "
+ "a group of agents or a single agent. Each worker is "
+ "created to solve a specific kind of task. Your job "
+ "includes assigning tasks to a existing worker, creating "
+ "a new worker for a task, etc.",
+ )
+ self.coordinator_agent = ChatAgent(
+ coord_agent_sys_msg, **(coordinator_agent_kwargs or {})
+ )
+
+ task_sys_msg = BaseMessage.make_assistant_message(
+ role_name="Task Planner",
+ content="You are going to compose and decompose tasks.",
+ )
+ self.task_agent = ChatAgent(task_sys_msg, **(task_agent_kwargs or {}))
+
+ # If there is one, will set by the workforce class wrapping this
+ self._task: Optional[Task] = None
+ self._pending_tasks: Deque[Task] = deque()
+
+ def __repr__(self):
+ return f"Workforce {self.node_id} ({self.description})"
+
+ def _decompose_task(self, task: Task) -> List[Task]:
+ r"""Decompose the task into subtasks. This method will also set the
+ relationship between the task and its subtasks.
+ Returns:
+ List[Task]: The subtasks.
+ """
+ decompose_prompt = WF_TASK_DECOMPOSE_PROMPT.format(
+ content=task.content,
+ child_nodes_info=self._get_child_nodes_info(),
+ additional_info=task.additional_info,
+ )
+ self.task_agent.reset()
+ subtasks = task.decompose(self.task_agent, decompose_prompt)
+ task.subtasks = subtasks
+ for subtask in subtasks:
+ subtask.parent = task
+
+ return subtasks
+
+ @check_if_running(False)
def process_task(self, task: Task) -> Task:
- self._root_node.set_main_task(task)
- shared_channel = TaskChannel()
- self._root_node.set_channel(shared_channel)
+ r"""The main entry point for the workforce to process a task. It will
+ start the workforce and all the child nodes under it, process the
+ task provided and return the updated task.
+
+ Args:
+ task (Task): The task to be processed.
+
+ Returns:
+ Task: The updated task.
+ """
+ self.reset()
+ self._task = task
+ task.state = TaskState.FAILED
+ self._pending_tasks.append(task)
+ # The agent tend to be overconfident on the whole task, so we
+ # decompose the task into subtasks first
+ subtasks = self._decompose_task(task)
+ self._pending_tasks.extendleft(reversed(subtasks))
+ self.set_channel(TaskChannel())
- # start the root workforce
- asyncio.run(self._root_node.start())
+ asyncio.run(self.start())
return task
+
+ @check_if_running(False)
+ def add_single_agent_worker(
+ self, description: str, worker: ChatAgent
+ ) -> Workforce:
+ r"""Add a worker node to the workforce that uses a single agent.
+
+ Args:
+ description (str): Description of the worker node.
+ worker (ChatAgent): The agent to be added.
+
+ Returns:
+ Workforce: The workforce node itself.
+ """
+ worker_node = SingleAgentWorker(description, worker)
+ self._children.append(worker_node)
+ return self
+
+ @check_if_running(False)
+ def add_role_playing_worker(
+ self,
+ description: str,
+ assistant_role_name: str,
+ user_role_name: str,
+ assistant_agent_kwargs: Optional[Dict] = None,
+ user_agent_kwargs: Optional[Dict] = None,
+ chat_turn_limit: int = 3,
+ ) -> Workforce:
+ r"""Add a worker node to the workforce that uses `RolePlaying` system.
+
+ Args:
+ description (str): Description of the node.
+ assistant_role_name (str): The role name of the assistant agent.
+ user_role_name (str): The role name of the user agent.
+ assistant_agent_kwargs (Optional[Dict], optional): The keyword
+ arguments to initialize the assistant agent in the role
+ playing, like the model name, etc. Defaults to `None`.
+ user_agent_kwargs (Optional[Dict], optional): The keyword arguments
+ to initialize the user agent in the role playing, like the
+ model name, etc. Defaults to `None`.
+ chat_turn_limit (int, optional): The maximum number of chat turns
+ in the role playing. Defaults to 3.
+
+ Returns:
+ Workforce: The workforce node itself.
+ """
+ worker_node = RolePlayingWorker(
+ description,
+ assistant_role_name,
+ user_role_name,
+ assistant_agent_kwargs,
+ user_agent_kwargs,
+ chat_turn_limit,
+ )
+ self._children.append(worker_node)
+ return self
+
+ @check_if_running(False)
+ def add_workforce(self, workforce: Workforce) -> Workforce:
+ r"""Add a workforce node to the workforce.
+
+ Args:
+ workforce (Workforce): The workforce node to be added.
+
+ Returns:
+ Workforce: The workforce node itself.
+ """
+ self._children.append(workforce)
+ return self
+
+ @check_if_running(False)
+ def reset(self) -> None:
+ r"""Reset the workforce and all the child nodes under it. Can only
+ be called when the workforce is not running."""
+ super().reset()
+ self._task = None
+ self._pending_tasks.clear()
+ self._child_listening_tasks.clear()
+ self.coordinator_agent.reset()
+ self.task_agent.reset()
+ for child in self._children:
+ child.reset()
+
+ @check_if_running(False)
+ def set_channel(self, channel: TaskChannel) -> None:
+ r"""Set the channel for the node and all the child nodes under it."""
+ self._channel = channel
+ for child in self._children:
+ child.set_channel(channel)
+
+ def _get_child_nodes_info(self) -> str:
+ r"""Get the information of all the child nodes under this node."""
+ info = ""
+ for child in self._children:
+ if isinstance(child, Workforce):
+ additional_info = "A Workforce node"
+ elif isinstance(child, SingleAgentWorker):
+ additional_info = "tools: " + (
+ ", ".join(child.worker.func_dict.keys())
+ )
+ elif isinstance(child, RolePlayingWorker):
+ additional_info = "A Role playing node"
+ else:
+ additional_info = "Unknown node"
+ info += (
+ f"<{child.node_id}>:<{child.description}>:<"
+ f"{additional_info}>\n"
+ )
+ return info
+
+ def _find_assignee(
+ self,
+ task: Task,
+ ) -> str:
+ r"""Assigns a task to a worker node with the best capability.
+
+ Parameters:
+ task (Task): The task to be assigned.
+
+ Returns:
+ str: ID of the worker node to be assigned.
+ """
+ self.coordinator_agent.reset()
+ prompt = ASSIGN_TASK_PROMPT.format(
+ content=task.content,
+ child_nodes_info=self._get_child_nodes_info(),
+ additional_info=task.additional_info,
+ )
+ req = BaseMessage.make_user_message(
+ role_name="User",
+ content=prompt,
+ )
+
+ response = self.coordinator_agent.step(
+ req, output_schema=TaskAssignResult
+ )
+ result_dict = ast.literal_eval(response.msg.content)
+ task_assign_result = TaskAssignResult(**result_dict)
+ return task_assign_result.assignee_id
+
+ async def _post_task(self, task: Task, assignee_id: str) -> None:
+ await self._channel.post_task(task, self.node_id, assignee_id)
+
+ async def _post_dependency(self, dependency: Task) -> None:
+ await self._channel.post_dependency(dependency, self.node_id)
+
+ def _create_worker_node_for_task(self, task: Task) -> Worker:
+ r"""Creates a new worker node for a given task and add it to the
+ children list of this node. This is one of the actions that
+ the coordinator can take when a task has failed.
+
+ Args:
+ task (Task): The task for which the worker node is created.
+
+ Returns:
+ Worker: The created worker node.
+ """
+ prompt = CREATE_NODE_PROMPT.format(
+ content=task.content,
+ child_nodes_info=self._get_child_nodes_info(),
+ additional_info=task.additional_info,
+ )
+ req = BaseMessage.make_user_message(
+ role_name="User",
+ content=prompt,
+ )
+ response = self.coordinator_agent.step(req, output_schema=WorkerConf)
+ result_dict = ast.literal_eval(response.msg.content)
+ new_node_conf = WorkerConf(**result_dict)
+
+ new_agent = self._create_new_agent(
+ new_node_conf.role,
+ new_node_conf.sys_msg,
+ )
+
+ new_node = SingleAgentWorker(
+ description=new_node_conf.description,
+ worker=new_agent,
+ )
+ new_node.set_channel(self._channel)
+
+ print(f"{Fore.CYAN}{new_node} created.{Fore.RESET}")
+
+ self._children.append(new_node)
+ self._child_listening_tasks.append(
+ asyncio.create_task(new_node.start())
+ )
+ return new_node
+
+ def _create_new_agent(self, role: str, sys_msg: str) -> ChatAgent:
+ worker_sys_msg = BaseMessage.make_assistant_message(
+ role_name=role,
+ content=sys_msg,
+ )
+
+ if self.new_worker_agent_kwargs is not None:
+ return ChatAgent(worker_sys_msg, **self.new_worker_agent_kwargs)
+
+ # Default tools for a new agent
+ function_list = [
+ *SEARCH_FUNCS,
+ *WEATHER_FUNCS,
+ *GoogleMapsToolkit().get_tools(),
+ ]
+
+ model_config_dict = ChatGPTConfig(
+ tools=function_list,
+ temperature=0.0,
+ ).as_dict()
+
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_4O,
+ model_config_dict=model_config_dict,
+ )
+
+ return ChatAgent(worker_sys_msg, model=model, tools=function_list)
+
+ async def _get_returned_task(self) -> Task:
+ r"""Get the task that's published by this node and just get returned
+ from the assignee.
+ """
+ return await self._channel.get_returned_task_by_publisher(self.node_id)
+
+ async def _post_ready_tasks(self) -> None:
+ r"""Send all the pending tasks that have all the dependencies met to
+ the channel, or directly return if there is none. For now, we will
+ directly send the first task in the pending list because all the tasks
+ are linearly dependent."""
+
+ if not self._pending_tasks:
+ return
+
+ ready_task = self._pending_tasks[0]
+
+ # If the task has failed previously, just compose and send the task
+ # to the channel as a dependency
+ if ready_task.state == TaskState.FAILED:
+ # TODO: the composing of tasks seems not work very well
+ self.task_agent.reset()
+ ready_task.compose(self.task_agent)
+ # Remove the subtasks from the channel
+ for subtask in ready_task.subtasks:
+ await self._channel.remove_task(subtask.id)
+ # Send the task to the channel as a dependency
+ await self._post_dependency(ready_task)
+ self._pending_tasks.popleft()
+ # Try to send the next task in the pending list
+ await self._post_ready_tasks()
+ else:
+ # Directly post the task to the channel if it's a new one
+ # Find a node to assign the task
+ assignee_id = self._find_assignee(task=ready_task)
+ await self._post_task(ready_task, assignee_id)
+
+ async def _handle_failed_task(self, task: Task) -> bool:
+ if task.failure_count >= 3:
+ return True
+ task.failure_count += 1
+ # Remove the failed task from the channel
+ await self._channel.remove_task(task.id)
+ if task.get_depth() >= 3:
+ # Create a new worker node and reassign
+ assignee = self._create_worker_node_for_task(task)
+ await self._post_task(task, assignee.node_id)
+ else:
+ subtasks = self._decompose_task(task)
+ # Insert packets at the head of the queue
+ self._pending_tasks.extendleft(reversed(subtasks))
+ await self._post_ready_tasks()
+ return False
+
+ async def _handle_completed_task(self, task: Task) -> None:
+ # archive the packet, making it into a dependency
+ self._pending_tasks.popleft()
+ await self._channel.archive_task(task.id)
+ await self._post_ready_tasks()
+
+ @check_if_running(False)
+ async def _listen_to_channel(self) -> None:
+ r"""Continuously listen to the channel, post task to the channel and
+ track the status of posted tasks.
+ """
+
+ self._running = True
+ logger.info(f"Workforce {self.node_id} started.")
+
+ await self._post_ready_tasks()
+
+ while self._task is None or self._pending_tasks:
+ returned_task = await self._get_returned_task()
+ if returned_task.state == TaskState.DONE:
+ await self._handle_completed_task(returned_task)
+ elif returned_task.state == TaskState.FAILED:
+ halt = await self._handle_failed_task(returned_task)
+ if not halt:
+ continue
+ print(
+ f"{Fore.RED}Task {returned_task.id} has failed "
+ f"for 3 times, halting the workforce.{Fore.RESET}"
+ )
+ break
+ elif returned_task.state == TaskState.OPEN:
+ # TODO: multi-layer workforce
+ pass
+ else:
+ raise ValueError(
+ f"Task {returned_task.id} has an unexpected state."
+ )
+
+ # shut down the whole workforce tree
+ self.stop()
+
+ @check_if_running(False)
+ async def start(self) -> None:
+ r"""Start itself and all the child nodes under it."""
+ for child in self._children:
+ child_listening_task = asyncio.create_task(child.start())
+ self._child_listening_tasks.append(child_listening_task)
+ await self._listen_to_channel()
+
+ @check_if_running(True)
+ def stop(self) -> None:
+ r"""Stop all the child nodes under it. The node itself will be stopped
+ by its parent node.
+ """
+ for child in self._children:
+ child.stop()
+ for child_task in self._child_listening_tasks:
+ child_task.cancel()
+ self._running = False
diff --git a/camel/workforce/workforce_prompt.py b/camel/workforce/workforce_prompt.py
deleted file mode 100644
index 3ef70d8f4..000000000
--- a/camel/workforce/workforce_prompt.py
+++ /dev/null
@@ -1,125 +0,0 @@
-# =========== 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 camel.prompts import TextPrompt
-
-# ruff: noqa: E501
-CREATE_NODE_PROMPT = TextPrompt(
- """You need to use the given information to create a new workforce for solving the category of tasks of the given one.
-The content of the given task is:
-
-{content}
-
-Following is the information of the existing workforces. The format is <ID>: <description>.
-
-{child_nodes_info}
-
-You must return the following information:
-1. The role of the agent working in the workforce, e.g. "programmer", "researcher", "product owner". This should be enclosed within the <role></role> tags.
-2. The system message that will be sent to the agent, enclosed within the <system></system> tags.
-3. The description of the workforce, enclosed within the <description></description> tags.
-
-Also, all of the info should be enclosed within a <workforce> tag. For example:
-
-<workforce>
-<role>programmer</role>
-<system>You are a python programmer.</system>
-<description>a python programmer.</description>
-</workforce>
-
-You should ensure that the workforce created is capable of solving all the tasks in the same category as the given one, don't make it too specific.
-Also, there should be no big overlap between the new workforce and the existing ones.
-The information returned should be concise and clear. Each pair of tag can only appear once.
-"""
-)
-
-ASSIGN_TASK_PROMPT = TextPrompt(
- """You need to assign the task to a workforce.
-The content of the task is:
-
-{content}
-
-Following is the information of the existing workforces. The format is <ID>: <description>.
-
-{child_nodes_info}
-
-You must return the ID of the workforce that you think is most capable of doing the task. The ID should be enclosed within the <id></id> tags, for example:
-
-<id>1</id>
-"""
-)
-
-PROCESS_TASK_PROMPT = TextPrompt(
- """You need to process the task. It is recommended that tools be actively called when needed.
-The content of the task is:
-
-{content}
-
-The type of the task is:
-
-{type}
-
-To process this task, here is some information on several dependent tasks:
-
-{dependency_task_info}
-
-You must return the result of the given task. The result should be enclosed within the <result></result> tags, for example:
-
-<result>Today, you requested information about the current weather conditions. The weather today in New York City is partly cloudy with a high of 75°F (24°C) and a low of 59°F (15°C). There is a 10 percent chance of rain with winds coming from the northeast at 5 mph. Humidity levels are at 60%. It's a perfect day to spend some time outdoors, perhaps in one of the city's beautiful parks.</result>
-
-if you are not able to process the task, you need to return <failed></failed> tags.
-"""
-)
-
-
-ROLEPLAY_PROCESS_TASK_PROMPT = TextPrompt(
- """You need to process the task. It is recommended that tools be actively called when needed.
-The content of the task is:
-
-{content}
-
-The type of the task is:
-
-{type}
-
-To process this task, here is some information on several dependent tasks:
-
-{dependency_task_info}
-
-You must return the result of the given task.
-
-"""
-)
-
-# TODO: improve prompt quality
-ROLEPLAY_SUMMERIZE_PROMPT = TextPrompt(
- """You need to process the task.
-The content of the task is:
-
-{content}
-
-The type of the task is:
-
-{type}
-
-To process this task, here are the chat history of AI user and AI assistant:
-
-{chat_history}
-
-You must summerize the chat history of the return the result of the given task. The result should be enclosed within the <result></result> tags, for example:
-
-<result>Today, you requested information about the current weather conditions. The weather today in New York City is partly cloudy with a high of 75°F (24°C) and a low of 59°F (15°C). There is a 10 percent chance of rain with winds coming from the northeast at 5 mph. Humidity levels are at 60%. It's a perfect day to spend some time outdoors, perhaps in one of the city's beautiful parks.</result>
-
-if you are not able to process the task, you need to return <failed></failed> tags.
-"""
-)
diff --git a/examples/workforce/hackathon_judges.py b/examples/workforce/hackathon_judges.py
new file mode 100644
index 000000000..ed993b219
--- /dev/null
+++ b/examples/workforce/hackathon_judges.py
@@ -0,0 +1,263 @@
+# =========== 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 textwrap
+
+from camel.agents import ChatAgent
+from camel.configs import ChatGPTConfig
+from camel.messages import BaseMessage
+from camel.models import ModelFactory
+from camel.tasks import Task
+from camel.toolkits import OpenAIFunction, SearchToolkit
+from camel.types import ModelPlatformType, ModelType
+from camel.workforce import Workforce
+
+
+def make_judge(
+ persona: str,
+ example_feedback: str,
+ criteria: str,
+) -> ChatAgent:
+ msg_content = textwrap.dedent(
+ f"""\
+ You are a judge in a hackathon.
+ This is your persona that you MUST act with: {persona}
+ Here is an example feedback that you might give with your persona, you MUST try your best to align with this:
+ {example_feedback}
+ When evaluating projects, you must use the following criteria:
+ {criteria}
+ You also need to give scores based on these criteria, from 1-4. The score given should be like 3/4, 2/4, etc.
+ """ # noqa: E501
+ )
+
+ sys_msg = BaseMessage.make_assistant_message(
+ role_name="Hackathon Judge",
+ content=msg_content,
+ )
+
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_4O,
+ model_config_dict=ChatGPTConfig().as_dict(),
+ )
+
+ agent = ChatAgent(
+ system_message=sys_msg,
+ model=model,
+ )
+
+ return agent
+
+
+def main():
+ proj_content = textwrap.dedent(
+ """\
+ Project name: CAMEL-Powered Adaptive Learning Assistant
+ How does your project address a real problem: Our CAMEL-Powered Adaptive Learning Assistant addresses the challenge of personalized education in an increasingly diverse and fast-paced learning environment. Traditional one-size-fits-all approaches to education often fail to meet the unique needs of individual learners, leading to gaps in understanding and reduced engagement. Our project leverages CAMEL-AI's advanced capabilities to create a highly adaptive, intelligent tutoring system that can understand and respond to each student's learning style, pace, and knowledge gaps in real-time.
+ Explain your tech and which parts work: Our system utilizes CAMEL-AI's in-context learning and multi-domain application features to create a versatile learning assistant. The core components include:
+ 1. Learner Profile Analysis: Uses natural language processing to assess the student's current knowledge, learning preferences, and goals.
+ 2. Dynamic Content Generation: Leverages CAMEL-AI to create personalized learning materials, explanations, and practice questions tailored to each student's needs.
+ 3. Adaptive Feedback Loop: Continuously analyzes student responses and adjusts the difficulty and style of content in real-time.
+ 4. Multi-Modal Integration: Incorporates text, images, and interactive elements to cater to different learning styles.
+ 5. Progress Tracking: Provides detailed insights into the student's learning journey, identifying strengths and areas for improvement.
+ Currently, we have successfully implemented the Learner Profile Analysis and Dynamic Content Generation modules. The Adaptive Feedback Loop is partially functional, while the Multi-Modal Integration and Progress Tracking features are still in development.
+ """ # noqa: E501
+ )
+
+ search_toolkit = SearchToolkit()
+ search_tools = [
+ OpenAIFunction(search_toolkit.search_google),
+ OpenAIFunction(search_toolkit.search_duckduckgo),
+ ]
+
+ researcher_model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_4O,
+ model_config_dict=ChatGPTConfig().as_dict(),
+ )
+
+ researcher_agent = ChatAgent(
+ system_message=BaseMessage.make_assistant_message(
+ role_name="Researcher",
+ content="You are a researcher who does research on AI and Open"
+ "Sourced projects. You use web search to stay updated on the "
+ "latest innovations and trends.",
+ ),
+ model=researcher_model,
+ tools=search_tools,
+ )
+
+ vc_persona = (
+ 'You are a venture capitalist who is obsessed with how projects can '
+ 'be scaled into "unicorn" companies. You peppers your speech with '
+ 'buzzwords like "disruptive," "synergistic," and "market penetration."'
+ ' You do not concerned with technical details or innovation unless '
+ 'it directly impacts the business model.'
+ )
+
+ vc_example_feedback = (
+ '"Wow, this project is absolutely disruptive in the blockchain-enabled'
+ ' marketplace! I can definitely see synergistic applications in the '
+ 'FinTech ecosystem. The scalability is through the roof--this is '
+ 'revolutionary!'
+ )
+
+ vc_criteria = textwrap.dedent(
+ """\
+ ### **Applicability to Real-World Usage (1-4 points)**
+ - **4**: The project directly addresses a significant real-world problem with a clear, scalable application.
+ - **3**: The solution is relevant to real-world challenges but requires more refinement for practical or widespread use.
+ - **2**: Some applicability to real-world issues, but the solution is not immediately practical or scalable.
+ - **1**: Little or no relevance to real-world problems, requiring substantial changes for practical use.
+ """ # noqa: E501
+ )
+
+ vc_agent = make_judge(
+ vc_persona,
+ vc_example_feedback,
+ vc_criteria,
+ )
+
+ eng_persona = (
+ 'You are an experienced engineer and a perfectionist. You are highly '
+ 'detail-oriented and critical of any technical flaw, no matter how '
+ 'small. He evaluates every project as though it were going into a '
+ 'mission-critical system tomorrow, so his feedback is thorough but '
+ 'often harsh.'
+ )
+
+ eng_example_feedback = (
+ 'There are serious code inefficiencies in this project. The '
+ 'architecture is unstable, and the memory management is suboptimal. '
+ 'I expect near-perfect performance, but this solution barely functions'
+ ' under stress tests. It has potential, but it is nowhere near '
+ 'deployment-ready.'
+ )
+
+ eng_criteria = textwrap.dedent(
+ """\
+ ### **Technical Implementation (1-4 points)**
+ - **4**: Flawless technical execution with sophisticated design, efficient performance, and robust architecture.
+ - **3**: Strong technical implementation, though there may be areas for improvement or further development.
+ - **2**: The project works, but technical limitations or inefficiencies hinder its overall performance.
+ - **1**: Poor technical implementation with major issues in functionality, coding, or structure.
+ """ # noqa: E501
+ )
+
+ eng_agent = make_judge(
+ eng_persona,
+ eng_example_feedback,
+ eng_criteria,
+ )
+
+ founder_persona = (
+ 'You are a well-known AI startup founder who is always looking for the'
+ ' "next big thing" in AI. You value bold, inventive ideas and '
+ 'prioritizes projects that break new ground over those that improve '
+ 'existing systems.'
+ )
+
+ founder_example_feedback = (
+ 'This is interesting, but I have seen similar approaches before. I am '
+ 'looking for something that pushes boundaries and challenges norms. '
+ 'What is the most revolutionary part of this project? Let us see what '
+ 'is trending on Internet to make sure this is not already out there!'
+ )
+
+ founder_criteria = textwrap.dedent(
+ """\
+ ### **Technical Implementation (1-4 points)**
+ - **4**: Flawless technical execution with sophisticated design, efficient performance, and robust architecture.
+ - **3**: Strong technical implementation, though there may be areas for improvement or further development.
+ - **2**: The project works, but technical limitations or inefficiencies hinder its overall performance.
+ - **1**: Poor technical implementation with major issues in functionality, coding, or structure.
+ """ # noqa: E501
+ )
+
+ founder_agent = make_judge(
+ founder_persona,
+ founder_example_feedback,
+ founder_criteria,
+ )
+
+ contributor_persona = (
+ 'You are a contributor to the CAMEL-AI project and is always excited '
+ 'to see how people are using it. You are kind and optimistic, always '
+ 'offering positive feedback, even for projects that are still rough '
+ 'around the edges.'
+ )
+
+ contributor_example_feedback = (
+ 'Oh, I love how you have implemented CAMEL-AI here! The use of its '
+ 'adaptive learning capabilities is fantastic, and you have really '
+ 'leveraged the contextual reasoning in a great way! Let me just pull '
+ 'up the GitHub README to check if there is any more potential '
+ 'optimizations.'
+ )
+
+ contributor_criteria = textwrap.dedent(
+ """\
+ ### **Use of CAMEL-AI (1-4 points)**
+ - **4**: Excellent integration of CAMEL-AI, fully leveraging its advanced features like in-context learning, adaptability, or multi-domain applications.
+ - **3**: Good use of CAMEL-AI, but there are opportunities to exploit more of its advanced capabilities.
+ - **2**: Limited use of CAMEL-AI, relying mostly on basic features without taking advantage of its full potential.
+ - **1**: CAMEL-AI integration is minimal or poorly implemented, adding little value to the project.
+ """ # noqa: E501
+ )
+
+ contributor_agent = make_judge(
+ contributor_persona,
+ contributor_example_feedback,
+ contributor_criteria,
+ )
+
+ workforce = Workforce('Hackathon Judges')
+ task = Task(
+ content="Evaluate the hackathon project. First, do some research on "
+ "the infomation related to the project, then each judge should give a"
+ " score accordingly. Finally, list the opinions from each judge while"
+ " preserving the judge's unique identity, along with the score and"
+ " judge name, and also give a final summary of the opinions.",
+ additional_info=proj_content,
+ id="0",
+ )
+
+ workforce.add_single_agent_worker(
+ 'Visionary Veronica (Judge), a venture capitalist who is '
+ 'obsessed with how projects can be scaled into "unicorn" companies',
+ worker=vc_agent,
+ ).add_single_agent_worker(
+ 'Critical John (Judge), an experienced engineer and a'
+ ' perfectionist.',
+ worker=eng_agent,
+ ).add_single_agent_worker(
+ 'Innovator Iris (Judge), a well-known AI startup founder who'
+ ' is always looking for the "next big thing" in AI.',
+ worker=founder_agent,
+ ).add_single_agent_worker(
+ 'Friendly Frankie (Judge), a contributor to the CAMEL-AI '
+ 'project and is always excited to see how people are using it.',
+ worker=contributor_agent,
+ ).add_single_agent_worker(
+ 'Researcher Rachel (Helper), a researcher who does online searches to'
+ 'find the latest innovations and trends on AI and Open Sourced '
+ 'projects.',
+ worker=researcher_agent,
+ )
+
+ task = workforce.process_task(task)
+ print(task.result)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/workforce/multiple_single_agents.py b/examples/workforce/multiple_single_agents.py
index ecd28d6ad..878bc6441 100644
--- a/examples/workforce/multiple_single_agents.py
+++ b/examples/workforce/multiple_single_agents.py
@@ -17,89 +17,90 @@ from camel.configs.openai_config import ChatGPTConfig
from camel.messages.base import BaseMessage
from camel.models import ModelFactory
from camel.tasks.task import Task
-from camel.toolkits import SEARCH_FUNCS, WEATHER_FUNCS, GoogleMapsToolkit
+from camel.toolkits import (
+ WEATHER_FUNCS,
+ GoogleMapsToolkit,
+ OpenAIFunction,
+ SearchToolkit,
+)
from camel.types import ModelPlatformType, ModelType
-from camel.workforce.manager_node import ManagerNode
-from camel.workforce.single_agent_node import SingleAgentNode
-from camel.workforce.workforce import Workforce
+from camel.workforce import Workforce
def main():
- # set the tools for the tool_agent
- tools_list = [
- *SEARCH_FUNCS,
- *WEATHER_FUNCS,
- *GoogleMapsToolkit().get_tools(),
+ search_toolkit = SearchToolkit()
+ search_tools = [
+ OpenAIFunction(search_toolkit.search_google),
+ OpenAIFunction(search_toolkit.search_duckduckgo),
]
- # configure the model of tool_agent
- model_config_dict = ChatGPTConfig(
- temperature=0.0,
- ).as_dict()
- model = ModelFactory.create(
+ # Set up web searching agent
+ search_agent_model = ModelFactory.create(
model_platform=ModelPlatformType.OPENAI,
- model_type=ModelType.GPT_4O_MINI,
- model_config_dict=model_config_dict,
+ model_type=ModelType.GPT_4O,
+ model_config_dict=ChatGPTConfig().as_dict(),
)
-
- # set tool_agent
- tool_agent = ChatAgent(
+ search_agent = ChatAgent(
system_message=BaseMessage.make_assistant_message(
- role_name="Tools calling opertor",
- content="You are a helpful assistant",
+ role_name="Web searching agent",
+ content="You can search online for information",
),
- model=model,
- tools=tools_list,
+ model=search_agent_model,
+ tools=[*search_tools, *WEATHER_FUNCS],
+ )
+
+ # Set up tour guide agent
+ tour_guide_agent_model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_4O,
+ model_config_dict=ChatGPTConfig().as_dict(),
)
- # set tour_guide_agent
+
tour_guide_agent = ChatAgent(
BaseMessage.make_assistant_message(
- role_name="tour guide",
- content="You have to lead everyone to have fun",
- )
+ role_name="Tour guide",
+ content="You are a tour guide",
+ ),
+ model=tour_guide_agent_model,
+ tools=GoogleMapsToolkit().get_tools(),
)
- # traveler_agent
+
+ # Set up traveler agent
traveler_agent = ChatAgent(
BaseMessage.make_assistant_message(
role_name="Traveler",
content="You can ask questions about your travel plans",
- )
+ ),
+ model=ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_4O,
+ model_config_dict=ChatGPTConfig().as_dict(),
+ ),
)
- # wrap the single agent into the worker nodes
- tour_guide_worker_node = SingleAgentNode(
- description='tour guide',
+ workforce = Workforce('A travel group')
+
+ workforce.add_single_agent_worker(
+ "A tour guide",
worker=tour_guide_agent,
+ ).add_single_agent_worker(
+ "A traveler", worker=traveler_agent
+ ).add_single_agent_worker(
+ "An agent who can do online searches", worker=search_agent
)
- traveler_worker_node = SingleAgentNode(
- description='Traveler', worker=traveler_agent
- )
- tool_worker_node = SingleAgentNode(
- description='Tools(eg.weather tools) calling opertor',
- worker=tool_agent,
- )
+
# specify the task to be solved
human_task = Task(
content=(
- "Plan a Paris tour itinerary for today"
- "taking into account the weather now."
+ "Plan a one-week trip to Paris, considering some historical places"
+ " to visit and weather conditions."
),
id='0',
)
- # create a manager node to combine all worker nodes
- root_node = ManagerNode(
- description='A travel group',
- children=[
- tour_guide_worker_node,
- traveler_worker_node,
- tool_worker_node,
- ],
- )
- workforce = Workforce(root_node)
task = workforce.process_task(human_task)
- print('Final Result of Origin task:\n', task.result)
+ print('Final Result of Original task:\n', task.result)
if __name__ == "__main__":
diff --git a/examples/workforce/role_playing_with_agents.py b/examples/workforce/role_playing_with_agents.py
index 0efeabe53..858860a69 100644
--- a/examples/workforce/role_playing_with_agents.py
+++ b/examples/workforce/role_playing_with_agents.py
@@ -17,12 +17,9 @@ from camel.configs.openai_config import ChatGPTConfig
from camel.messages.base import BaseMessage
from camel.models import ModelFactory
from camel.tasks.task import Task
-from camel.toolkits import MathToolkit, SearchToolkit, WeatherToolkit
+from camel.toolkits import SEARCH_FUNCS, WEATHER_FUNCS, GoogleMapsToolkit
from camel.types import ModelPlatformType, ModelType
-from camel.workforce.manager_node import ManagerNode
-from camel.workforce.role_playing_node import RolePlayingNode
-from camel.workforce.single_agent_node import SingleAgentNode
-from camel.workforce.workforce import Workforce
+from camel.workforce import Workforce
def main():
@@ -39,64 +36,51 @@ def main():
guide_agent = ChatAgent(guide_sysmsg)
planner_agent = ChatAgent(planner_sysmsg)
- guide_worker_node = SingleAgentNode('tour guide', guide_agent)
- planner_worker_node = SingleAgentNode('planner', planner_agent)
-
- tools_list = [
- *MathToolkit().get_tools(),
- *WeatherToolkit().get_tools(),
- *SearchToolkit().get_tools(),
+ function_list = [
+ *SEARCH_FUNCS,
+ *WEATHER_FUNCS,
+ *GoogleMapsToolkit().get_tools(),
]
- user_model_config = ChatGPTConfig(temperature=0.0)
- assistant_model_config = ChatGPTConfig(
- temperature=0.0,
- )
+
model_platform = ModelPlatformType.OPENAI
- model_type = ModelType.GPT_4O_MINI
+ model_type = ModelType.GPT_3_5_TURBO
assistant_role_name = "Searcher"
user_role_name = "Professor"
assistant_agent_kwargs = dict(
model=ModelFactory.create(
model_platform=model_platform,
model_type=model_type,
- model_config_dict=assistant_model_config.as_dict(),
+ model_config_dict=ChatGPTConfig().as_dict(),
),
- tools=tools_list,
+ tools=function_list,
)
user_agent_kwargs = dict(
model=ModelFactory.create(
model_platform=model_platform,
model_type=model_type,
- model_config_dict=user_model_config.as_dict(),
+ model_config_dict=ChatGPTConfig().as_dict(),
),
)
- research_rp_worker_node = RolePlayingNode(
+
+ workforce = Workforce('a travel group')
+ workforce.add_role_playing_worker(
'research Group',
assistant_role_name,
user_role_name,
assistant_agent_kwargs,
user_agent_kwargs,
1,
- )
+ ).add_single_agent_worker(
+ 'tour guide', guide_agent
+ ).add_single_agent_worker('planner', planner_agent)
human_task = Task(
content="research history of Paris and plan a tour.",
id='0',
)
-
- root_node = ManagerNode(
- description='a travel group',
- children=[
- guide_worker_node,
- planner_worker_node,
- research_rp_worker_node,
- ],
- )
-
- workforce = Workforce(root_node)
task = workforce.process_task(human_task)
- print('Final Result of Origin task:\n', task.result)
+ print('Final result of original task:\n', task.result)
if __name__ == "__main__":
diff --git a/poetry.lock b/poetry.lock
index 5db59b3de..c51e00312 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -1,4 +1,4 @@
-# This file is automatically @generated by Poetry 1.8.2 and should not be changed by hand.
+# This file is automatically @generated by Poetry 1.8.3 and should not be changed by hand.
[[package]]
name = "accelerate"
@@ -2568,13 +2568,13 @@ files = [
[[package]]
name = "identify"
-version = "2.6.0"
+version = "2.6.1"
description = "File identification library for Python"
optional = false
python-versions = ">=3.8"
files = [
- {file = "identify-2.6.0-py2.py3-none-any.whl", hash = "sha256:e79ae4406387a9d300332b5fd366d8994f1525e8414984e1a59e058b2eda2dd0"},
- {file = "identify-2.6.0.tar.gz", hash = "sha256:cb171c685bdc31bcc4c1734698736a7d5b6c8bf2e0c15117f4d469c8640ae5cf"},
+ {file = "identify-2.6.1-py2.py3-none-any.whl", hash = "sha256:53863bcac7caf8d2ed85bd20312ea5dcfc22226800f6d6881f232d861db5a8f0"},
+ {file = "identify-2.6.1.tar.gz", hash = "sha256:91478c5fb7c3aac5ff7bf9b4344f803843dc586832d5f110d672b19aa1984c98"},
]
[package.extras]
@@ -3282,13 +3282,13 @@ files = [
[[package]]
name = "litellm"
-version = "1.45.0"
+version = "1.46.0"
description = "Library to easily interface with LLM API providers"
optional = true
python-versions = "!=2.7.*,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,!=3.7.*,>=3.8"
files = [
- {file = "litellm-1.45.0-py3-none-any.whl", hash = "sha256:87d712beabc6cbf24437557186c5b266729f3139bf7dd2e54573e1e9845b905a"},
- {file = "litellm-1.45.0.tar.gz", hash = "sha256:21285496e72b9b16ff9d3d1332965c3d1a9b0ae8dbb26f27a7080af28a117174"},
+ {file = "litellm-1.46.0-py3-none-any.whl", hash = "sha256:40209dc6368677d03b21b2c9d9cb91937c9648f741d42bb5a8f992a1cd31fb42"},
+ {file = "litellm-1.46.0.tar.gz", hash = "sha256:6707eb4b17a2eca714f81261c3b6f33297cd25470c4843b8297e345ebdff0560"},
]
[package.dependencies]
@@ -5380,6 +5380,7 @@ description = "Pure-Python implementation of ASN.1 types and DER/BER/CER codecs
optional = true
python-versions = ">=3.8"
files = [
+ {file = "pyasn1-0.6.1-py3-none-any.whl", hash = "sha256:0d632f46f2ba09143da3a8afe9e33fb6f92fa2320ab7e886e2d0f7672af84629"},
{file = "pyasn1-0.6.1.tar.gz", hash = "sha256:6f580d2bdd84365380830acf45550f2511469f673cb4a5ae3857a3170128b034"},
]
@@ -5390,6 +5391,7 @@ description = "A collection of ASN.1-based protocols modules"
optional = true
python-versions = ">=3.8"
files = [
+ {file = "pyasn1_modules-0.4.1-py3-none-any.whl", hash = "sha256:49bfa96b45a292b711e986f222502c1c9a5e1f4e568fc30e2574a6c7d07838fd"},
{file = "pyasn1_modules-0.4.1.tar.gz", hash = "sha256:c28e2dbf9c06ad61c71a075c7e0f9fd0f1b0bb2d2ad4377f240d33ac2ab60a7c"},
]
@@ -5845,15 +5847,18 @@ files = [
[[package]]
name = "pyreadline3"
-version = "3.4.3"
+version = "3.5.2"
description = "A python implementation of GNU readline."
optional = true
-python-versions = "*"
+python-versions = ">=3.8"
files = [
- {file = "pyreadline3-3.4.3-py3-none-any.whl", hash = "sha256:f832c5898f4f9a0f81d48a8c499b39d0179de1a465ea3def1a7e7231840b4ed6"},
- {file = "pyreadline3-3.4.3.tar.gz", hash = "sha256:ebab0baca37f50e2faa1dd99a6da1c75de60e0d68a3b229c134bbd12786250e2"},
+ {file = "pyreadline3-3.5.2-py3-none-any.whl", hash = "sha256:a87d56791e2965b2b187e2ea33dcf664600842c997c0623c95cf8ef07db83de9"},
+ {file = "pyreadline3-3.5.2.tar.gz", hash = "sha256:ba82292e52c5a3bb256b291af0c40b457c1e8699cac9a873abbcaac8aef3a1bb"},
]
+[package.extras]
+dev = ["build", "flake8", "pytest", "twine"]
+
[[package]]
name = "pysocks"
version = "1.7.1"
diff --git a/test/workforce/test_single_agent.py b/test/workforce/test_workforce_single_agent.py
similarity index 88%
rename from test/workforce/test_single_agent.py
rename to test/workforce/test_workforce_single_agent.py
index f67e103dc..f15cfbe66 100644
--- a/test/workforce/test_single_agent.py
+++ b/test/workforce/test_workforce_single_agent.py
@@ -16,7 +16,7 @@ import pytest
from camel.agents.chat_agent import ChatAgent
from camel.messages.base import BaseMessage
from camel.tasks.task import Task
-from camel.workforce.single_agent_node import SingleAgentNode
+from camel.workforce.single_agent_worker import SingleAgentWorker
@pytest.mark.asyncio
@@ -26,14 +26,13 @@ async def test_get_dep_tasks_info():
content="You are a python programmer.",
)
agent = ChatAgent(sys_msg)
- test_workforce = SingleAgentNode('agent1', agent)
+ test_worker = SingleAgentWorker('agent1', agent)
human_task = Task(
content='develop a python program of investing stock.',
id='0',
- type='human',
)
subtasks = human_task.decompose(agent) # TODO: use MagicMock
- await test_workforce._process_task(
+ await test_worker._process_task(
human_task, subtasks
) # TODO: use MagicMock