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

docs: Update the missing docstrings on different modules (#911) (#1079)

Xiaotian Jin3c1c3a1d6378
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.py
index d6e77f50d..1c5f9a2c4 100644
--- a/camel/agents/chat_agent.py
+++ b/camel/agents/chat_agent.py
@@ -106,6 +106,11 @@ class FunctionCallingRecord(BaseModel):
)
def as_dict(self) -> dict[str, Any]:
+ r"""Returns the function calling record as a dictionary.
+
+ Returns:
+ dict[str, Any]: The function calling record as a dictionary.
+ """
return self.model_dump()
@@ -221,6 +226,15 @@ class ChatAgent(BaseAgent):
# ruff: noqa: E501
def _generate_tool_prompt(self, tool_schema_list: List[Dict]) -> str:
+ r"""Generates a tool prompt based on the provided tool schema list.
+
+ Args:
+ tool_schema_list (List[Dict]): A list of dictionaries, each
+ containing a tool schema.
+
+ Returns:
+ str: A string representing the tool prompt.
+ """
tool_prompts = []
for tool in tool_schema_list:
@@ -241,21 +255,36 @@ class ChatAgent(BaseAgent):
{tool_prompt_str}
- If you choose to call a function ONLY reply in the following format with no prefix or suffix:
+ If you choose to call a function ONLY reply in the following format with no
+ prefix or suffix:
- <function=example_function_name>{{"example_name": "example_value"}}</function>
+ <function=example_function_name>{{"example_name": "example_value"}}
+ </function>
Reminder:
- - Function calls MUST follow the specified format, start with <function= and end with </function>
+ - Function calls MUST follow the specified format, start with <function=
+ and end with </function>
- Required parameters MUST be specified
- Only call one function at a time
- Put the entire function call reply on one line
- - If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls
+ - If there is no function call available, answer the question like normal
+ with your current knowledge and do not tell the user about function calls
"""
'''
return final_prompt
def _parse_tool_response(self, response: str):
+ r"""Parses the tool response to extract the function name and
+ arguments.
+
+ Args:
+ response (str): The response from the model containing the
+ function call.
+
+ Returns:
+ Optional[Dict[str, Any]]: The parsed function name and arguments
+ if found, otherwise :obj:`None`.
+ """
function_regex = r"<function=(\w+)>(.*?)</function>"
match = re.search(function_regex, response)
@@ -270,12 +299,7 @@ class ChatAgent(BaseAgent):
return None
def reset(self):
- r"""Resets the :obj:`ChatAgent` to its initial state and returns the
- stored messages.
-
- Returns:
- List[BaseMessage]: The stored messages.
- """
+ r"""Resets the :obj:`ChatAgent` to its initial state."""
self.terminated = False
self.init_messages()
for terminator in self.response_terminators:
@@ -292,7 +316,7 @@ class ChatAgent(BaseAgent):
return self._system_message
@system_message.setter
- def system_message(self, message: BaseMessage):
+ def system_message(self, message: BaseMessage) -> None:
r"""The setter method for the property :obj:`system_message`.
Args:
@@ -827,6 +851,17 @@ class ChatAgent(BaseAgent):
]:
r"""Internal function of structuring the output of the agent based on
the given output schema.
+
+ Args:
+ response_format (Type[BaseModel]): The output schema to use for
+ structuring the output.
+
+ Returns:
+ Tuple[List[BaseMessage], List[str], Dict[str, int], str,
+ FunctionCallingRecord, int]:
+ A tuple containing the output messages, finish reasons, usage
+ dictionary, response ID, function calling record, and number of
+ tokens.
"""
from camel.toolkits import FunctionTool
@@ -919,9 +954,39 @@ class ChatAgent(BaseAgent):
num_tokens: int,
external_tool_request: Optional[ChatCompletionMessageToolCall] = None,
) -> Dict[str, Any]:
- # Loop over responses terminators, get list of termination
- # tuples with whether the terminator terminates the agent
- # and termination reason
+ r"""Process the output of a chat step and gather information about the
+ step.
+
+ This method checks for termination conditions, updates the agent's
+ state, and collects information about the chat step, including tool
+ calls and termination reasons.
+
+ Args:
+ output_messages (List[BaseMessage]): The messages generated in
+ this step.
+ finish_reasons (List[str]): The reasons for finishing the
+ generation for each message.
+ usage_dict (Dict[str, int]): Dictionary containing token usage
+ information.
+ response_id (str): The ID of the response from the model.
+ tool_calls (List[FunctionCallingRecord]): Records of function calls
+ made during this step.
+ num_tokens (int): The number of tokens used in this step.
+ external_tool_request (Optional[ChatCompletionMessageToolCall]):
+ Any external tool request made during this step.
+ (default::obj:`None`)
+
+ Returns:
+ Dict[str, Any]: A dictionary containing information about the chat
+ step, including termination status, reasons, and tool call
+ information.
+
+ Note:
+ This method iterates over all response terminators and checks if
+ any of them signal termination. If a terminator signals
+ termination, the agent's state is updated accordingly, and the
+ termination reason is recorded.
+ """
termination = [
terminator.is_terminated(output_messages)
for terminator in self.response_terminators
@@ -952,7 +1017,8 @@ class ChatAgent(BaseAgent):
def handle_batch_response(
self, response: ChatCompletion
) -> Tuple[List[BaseMessage], List[str], Dict[str, int], str]:
- r"""
+ r"""Process a batch response from the model and extract the necessary
+ information.
Args:
response (dict): Model response.
@@ -985,7 +1051,18 @@ class ChatAgent(BaseAgent):
response.id,
)
- def _safe_model_dump(self, obj):
+ def _safe_model_dump(self, obj) -> dict:
+ r"""Safely dump a Pydantic model to a dictionary.
+
+ This method attempts to use the `model_dump` method if available,
+ otherwise it falls back to the `dict` method.
+
+ Args:
+ obj: The Pydantic model instance to be dumped.
+
+ Returns:
+ dict: A dictionary representation of the Pydantic model.
+ """
# Check if the `model_dump` method exists (Pydantic v2)
if hasattr(obj, 'model_dump'):
return obj.model_dump()
@@ -1000,7 +1077,8 @@ class ChatAgent(BaseAgent):
response: Stream[ChatCompletionChunk],
prompt_tokens: int,
) -> Tuple[List[BaseMessage], List[str], Dict[str, int], str]:
- r"""
+ r"""Process a stream response from the model and extract the necessary
+ information.
Args:
response (dict): Model response.
diff --git a/camel/configs/base_config.py b/camel/configs/base_config.py
index 8ce9ff24a..8690035cc 100644
--- a/camel/configs/base_config.py
+++ b/camel/configs/base_config.py
@@ -20,6 +20,12 @@ from pydantic import BaseModel, ConfigDict, field_validator
class BaseConfig(ABC, BaseModel):
+ r"""Base configuration class for all models.
+
+ This class provides a common interface for all models, ensuring that all
+ models have a consistent set of attributes and methods.
+ """
+
model_config = ConfigDict(
arbitrary_types_allowed=True,
extra="forbid",
@@ -38,6 +44,12 @@ class BaseConfig(ABC, BaseModel):
@field_validator("tools", mode="before")
@classmethod
def fields_type_checking(cls, tools):
+ r"""Validate the type of tools in the configuration.
+
+ This method ensures that the tools provided in the configuration are
+ instances of `FunctionTool`. If any tool is not an instance of
+ `FunctionTool`, it raises a ValueError.
+ """
if tools is not None:
from camel.toolkits import FunctionTool
@@ -50,6 +62,15 @@ class BaseConfig(ABC, BaseModel):
return tools
def as_dict(self) -> dict[str, Any]:
+ r"""Convert the current configuration to a dictionary.
+
+ This method converts the current configuration object to a dictionary
+ representation, which can be used for serialization or other purposes.
+
+ Returns:
+ dict[str, Any]: A dictionary representation of the current
+ configuration.
+ """
config_dict = self.model_dump()
tools_schema = None
diff --git a/camel/configs/gemini_config.py b/camel/configs/gemini_config.py
index 4abe91274..d2c29ae3c 100644
--- a/camel/configs/gemini_config.py
+++ b/camel/configs/gemini_config.py
@@ -87,6 +87,12 @@ class GeminiConfig(BaseConfig):
@model_validator(mode="before")
@classmethod
def model_type_checking(cls, data: Any):
+ r"""Validate the type of tools in the configuration.
+
+ This method ensures that the tools provided in the configuration are
+ instances of `FunctionTool`. If any tool is not an instance of
+ `FunctionTool`, it raises a ValueError.
+ """
if isinstance(data, dict):
response_schema = data.get("response_schema")
safety_settings = data.get("safety_settings")
@@ -111,16 +117,17 @@ class GeminiConfig(BaseConfig):
if response_schema and not isinstance(response_schema, Schema):
raise ValueError(
- "The response_schema should be "
- "an instance of `google.generativeai.protos.Schema`."
+ "The response_schema should be an instance of "
+ "google.generativeai.protos.Schema."
)
if safety_settings and not isinstance(
safety_settings, SafetySettingOptions
):
raise ValueError(
- "The response_schema should be an instance of "
- "`google.generativeai.types.safety_types.SafetySettingOptions`."
+ "The safety_settings should be an instance of "
+ "google.generativeai.types.safety_types."
+ "SafetySettingOptions."
)
if tools is not None:
@@ -128,19 +135,20 @@ class GeminiConfig(BaseConfig):
if not isinstance(tool, FunctionLibraryType):
raise ValueError(
"The tool should be an instance of "
- "`google.generativeai.types.content_types.FunctionLibraryType`."
+ "google.generativeai.types.content_types."
+ "FunctionLibraryType."
)
if tool_config and not isinstance(tool_config, ToolConfigType):
raise ValueError(
- "The response_schema should be an instance of "
- "`google.generativeai.types.content_types.ToolConfigType`."
+ "The tool_config should be an instance of "
+ "google.generativeai.types.content_types.ToolConfigType."
)
if request_options and not isinstance(
request_options, RequestOptionsType
):
raise ValueError(
- "The response_schema should be an instance of "
- "`google.generativeai.types.helper_types.RequestOptionsType`."
+ "The request_options should be an instance of "
+ "google.generativeai.types.helper_types.RequestOptionsType."
)
return data
diff --git a/camel/generators.py b/camel/generators.py
index 85b73a45e..bccc6d26b 100644
--- a/camel/generators.py
+++ b/camel/generators.py
@@ -154,6 +154,21 @@ class SystemMessageGenerator:
class RoleNameGenerator:
+ r"""Role name generator for role-playing workers.
+
+ Args:
+ assistant_role_names_path (str, optional): The path to the file
+ containing the assistant role names.
+ (default: :obj:`"data/ai_society/assistant_roles.txt"`)
+ user_role_names_path (str, optional): The path to the file
+ containing the user role names.
+ (default: :obj:`"data/ai_society/user_roles.txt"`)
+ assistant_role_names (Optional[List[str]], optional): The list of
+ assistant role names. (default: :obj:`None`)
+ user_role_names (Optional[List[str]], optional): The list of user role
+ names. (default: :obj:`None`)
+ """
+
def __init__(
self,
assistant_role_names_path: str = "data/ai_society/assistant_roles.txt",
@@ -181,12 +196,25 @@ class RoleNameGenerator:
self.user_role_names = user_role_names
def from_role_files(self) -> Generator[Tuple, None, None]:
+ r"""Generate role names from the file.
+
+ Returns:
+ Generator[Tuple, None, None]: A generator that yields tuples of
+ assistant role names and user role names.
+ """
for assistant_role_name in self.assistant_role_names:
for user_role_name in self.user_role_names:
yield (assistant_role_name, user_role_name)
class AISocietyTaskPromptGenerator:
+ r"""Task prompt generator for AI society tasks.
+
+ Args:
+ num_tasks (int, optional): The number of tasks to generate.
+ (default: :obj:`10`)
+ """
+
def __init__(
self,
num_tasks: int = 10,
@@ -205,6 +233,20 @@ class AISocietyTaskPromptGenerator:
assistant_role_names_path: str = "data/ai_society/assistant_roles.txt",
user_role_names_path: str = "data/ai_society/user_roles.txt",
) -> Generator[Tuple[str, Tuple[str, str]], None, None]:
+ r"""Generate tasks from role files.
+
+ Args:
+ assistant_role_names_path (str, optional): The path to the file
+ containing the assistant role names.
+ (default: :obj:`"data/ai_society/assistant_roles.txt"`)
+ user_role_names_path (str, optional): The path to the file
+ containing the user role names.
+ (default: :obj:`"data/ai_society/user_roles.txt"`)
+
+ Returns:
+ Generator[Tuple[str, Tuple[str, str]], None, None]: A generator
+ that yields tuples of task prompts and role names.
+ """
roles_generator = RoleNameGenerator(
assistant_role_names_path, user_role_names_path
).from_role_files()
@@ -220,6 +262,16 @@ class AISocietyTaskPromptGenerator:
def from_role_generator(
self, role_generator: Generator[Tuple, None, None]
) -> Generator[Tuple[str, Tuple[str, str]], None, None]:
+ r"""Generate tasks from a role generator.
+
+ Args:
+ role_generator (Generator[Tuple, None, None]): A generator that
+ yields tuples of role names.
+
+ Returns:
+ Generator[Tuple[str, Tuple[str, str]], None, None]: A generator
+ that yields tuples of task prompts and role names.
+ """
for role_1, role_2 in role_generator:
generate_tasks_prompt = self.generate_tasks_prompt.format(
assistant_role=role_1,
@@ -231,6 +283,12 @@ class AISocietyTaskPromptGenerator:
class SingleTxtGenerator:
+ r"""Single text generator for role-playing workers.
+
+ Args:
+ text_file_path (str): The path to the file containing the text data.
+ """
+
def __init__(
self,
text_file_path: str,
@@ -242,11 +300,23 @@ class SingleTxtGenerator:
]
def from_role_files(self) -> Generator[str, None, None]:
+ r"""Generate text from the file.
+
+ Returns:
+ Generator[str, None, None]: A generator that yields the text data.
+ """
for data in self.data_list:
yield data
class CodeTaskPromptGenerator:
+ r"""Code task prompt generator for code tasks.
+
+ Args:
+ num_tasks (int, optional): The number of tasks to generate.
+ (default: :obj:`50`)
+ """
+
def __init__(
self,
num_tasks: int = 50,
@@ -262,6 +332,19 @@ class CodeTaskPromptGenerator:
languages_path: str = "data/code/languages.txt",
domains_path: str = "data/code/domains.txt",
) -> Generator[Tuple[TextPrompt, str, str], None, None]:
+ r"""Generate tasks from role files.
+
+ Args:
+ languages_path (str, optional): The path to the file containing
+ the language names. (default: :obj:`"data/code/languages.txt"`)
+ domains_path (str, optional): The path to the file containing
+ the domain names. (default: :obj:`"data/code/domains.txt"`)
+
+ Returns:
+ Generator[Tuple[TextPrompt, str, str], None, None]: A generator
+ that yields tuples of task prompts, language names, and domain
+ names.
+ """
language_generator = SingleTxtGenerator(
languages_path
).from_role_files()
@@ -279,4 +362,14 @@ class CodeTaskPromptGenerator:
def from_role_generator(
self, role_generator: Generator[Tuple, None, None]
) -> Generator[str, None, None]:
+ r"""Generate tasks from a role generator.
+
+ Args:
+ role_generator (Generator[Tuple, None, None]): A generator that
+ yields tuples of role names.
+
+ Returns:
+ Generator[str, None, None]: A generator that yields the task
+ prompts.
+ """
raise NotImplementedError
diff --git a/camel/interpreters/docker_interpreter.py b/camel/interpreters/docker_interpreter.py
index 764ae27b2..02d97e8e0 100644
--- a/camel/interpreters/docker_interpreter.py
+++ b/camel/interpreters/docker_interpreter.py
@@ -80,6 +80,11 @@ class DockerInterpreter(BaseInterpreter):
self._container: Optional[Container] = None
def __del__(self) -> None:
+ r"""Destructor for the DockerInterpreter class.
+
+ This method ensures that the Docker container is removed when the
+ interpreter is deleted.
+ """
if self._container is not None:
self._container.remove(force=True)
diff --git a/camel/interpreters/ipython_interpreter.py b/camel/interpreters/ipython_interpreter.py
index 03c8258be..9a0ebdcdf 100644
--- a/camel/interpreters/ipython_interpreter.py
+++ b/camel/interpreters/ipython_interpreter.py
@@ -105,7 +105,8 @@ class JupyterKernelInterpreter(BaseInterpreter):
outputs.append(msg_content["data"]["text/plain"])
if "image/png" in msg_content["data"]:
outputs.append(
- f"\n![image](data:image/png;base64,{msg_content['data']['image/png']})\n"
+ f"\n![image](data:image/png;base64,"
+ f"{msg_content['data']['image/png']})\n"
)
except queue.Empty:
outputs.append("Time out")
diff --git a/camel/memories/agent_memories.py b/camel/memories/agent_memories.py
index 7cd4c3729..3c4ca834c 100644
--- a/camel/memories/agent_memories.py
+++ b/camel/memories/agent_memories.py
@@ -106,7 +106,18 @@ class VectorDBMemory(AgentMemory):
class LongtermAgentMemory(AgentMemory):
r"""An implementation of the :obj:`AgentMemory` abstract base class for
- augumenting ChatHistoryMemory with VectorDBMemory.
+ augmenting ChatHistoryMemory with VectorDBMemory.
+
+ Args:
+ context_creator (BaseContextCreator): A model context creator.
+ chat_history_block (Optional[ChatHistoryBlock], optional): A chat
+ history block. If `None`, a :obj:`ChatHistoryBlock` will be used.
+ (default: :obj:`None`)
+ vector_db_block (Optional[VectorDBBlock], optional): A vector database
+ block. If `None`, a :obj:`VectorDBBlock` will be used.
+ (default: :obj:`None`)
+ retrieve_limit (int, optional): The maximum number of messages
+ to be added into the context. (default: :obj:`3`)
"""
def __init__(
@@ -123,9 +134,21 @@ class LongtermAgentMemory(AgentMemory):
self._current_topic: str = ""
def get_context_creator(self) -> BaseContextCreator:
+ r"""Returns the context creator used by the memory.
+
+ Returns:
+ BaseContextCreator: The context creator used by the memory.
+ """
return self._context_creator
def retrieve(self) -> List[ContextRecord]:
+ r"""Retrieves context records from both the chat history and the vector
+ database.
+
+ Returns:
+ List[ContextRecord]: A list of context records retrieved from both
+ the chat history and the vector database.
+ """
chat_history = self.chat_history_block.retrieve()
vector_db_retrieve = self.vector_db_block.retrieve(
self._current_topic, self.retrieve_limit
diff --git a/camel/messages/base.py b/camel/messages/base.py
index f58895250..19017edb2 100644
--- a/camel/messages/base.py
+++ b/camel/messages/base.py
@@ -81,6 +81,25 @@ class BaseMessage:
OpenAIVisionDetailType, str
] = OpenAIVisionDetailType.LOW,
) -> "BaseMessage":
+ r"""Create a new user message.
+
+ Args:
+ role_name (str): The name of the user role.
+ content (str): The content of the message.
+ meta_dict (Optional[Dict[str, str]]): Additional metadata
+ dictionary for the message.
+ video_bytes (Optional[bytes]): Optional bytes of a video
+ associated with the message.
+ image_list (Optional[List[Image.Image]]): Optional list of PIL
+ Image objects associated with the message.
+ image_detail (Union[OpenAIVisionDetailType, str]): Detail level of
+ the images associated with the message.
+ video_detail (Union[OpenAIVisionDetailType, str]): Detail level of
+ the videos associated with the message.
+
+ Returns:
+ BaseMessage: The new user message.
+ """
return cls(
role_name,
RoleType.USER,
@@ -107,6 +126,25 @@ class BaseMessage:
OpenAIVisionDetailType, str
] = OpenAIVisionDetailType.LOW,
) -> "BaseMessage":
+ r"""Create a new assistant message.
+
+ Args:
+ role_name (str): The name of the assistant role.
+ content (str): The content of the message.
+ meta_dict (Optional[Dict[str, str]]): Additional metadata
+ dictionary for the message.
+ video_bytes (Optional[bytes]): Optional bytes of a video
+ associated with the message.
+ image_list (Optional[List[Image.Image]]): Optional list of PIL
+ Image objects associated with the message.
+ image_detail (Union[OpenAIVisionDetailType, str]): Detail level of
+ the images associated with the message.
+ video_detail (Union[OpenAIVisionDetailType, str]): Detail level of
+ the videos associated with the message.
+
+ Returns:
+ BaseMessage: The new assistant message.
+ """
return cls(
role_name,
RoleType.ASSISTANT,
diff --git a/camel/prompts/image_craft.py b/camel/prompts/image_craft.py
index 0c7fb3deb..a0cd1a119 100644
--- a/camel/prompts/image_craft.py
+++ b/camel/prompts/image_craft.py
@@ -18,6 +18,14 @@ from camel.types import RoleType
class ImageCraftPromptTemplateDict(TextPromptDict):
+ r"""A dictionary containing :obj:`TextPrompt` used in the `ImageCraft`
+ task.
+
+ Attributes:
+ ASSISTANT_PROMPT (TextPrompt): A prompt for the AI assistant to create
+ an original image based on the provided descriptive captions.
+ """
+
ASSISTANT_PROMPT = TextPrompt(
"""You are tasked with creating an original image based on
the provided descriptive captions. Use your imagination
diff --git a/camel/prompts/video_description_prompt.py b/camel/prompts/video_description_prompt.py
index 7e5d141d8..77d6a3c4c 100644
--- a/camel/prompts/video_description_prompt.py
+++ b/camel/prompts/video_description_prompt.py
@@ -19,6 +19,14 @@ from camel.types import RoleType
# flake8: noqa :E501
class VideoDescriptionPromptTemplateDict(TextPromptDict):
+ r"""A dictionary containing :obj:`TextPrompt` used in the `VideoDescription`
+ task.
+
+ Attributes:
+ ASSISTANT_PROMPT (TextPrompt): A prompt for the AI assistant to
+ provide a shot description of the content of the current video.
+ """
+
ASSISTANT_PROMPT = TextPrompt(
"""You are a master of video analysis.
Please provide a shot description of the content of the current video."""
diff --git a/camel/societies/workforce/base.py b/camel/societies/workforce/base.py
index 4d505b869..1286d3b87 100644
--- a/camel/societies/workforce/base.py
+++ b/camel/societies/workforce/base.py
@@ -19,6 +19,12 @@ from camel.societies.workforce.utils import check_if_running
class BaseNode(ABC):
+ r"""Base class for all nodes in the workforce.
+
+ Args:
+ description (str): Description of the node.
+ """
+
def __init__(self, description: str) -> None:
self.node_id = str(id(self))
self.description = description
@@ -27,7 +33,7 @@ class BaseNode(ABC):
@check_if_running(False)
def reset(self, *args: Any, **kwargs: Any) -> Any:
- """Resets the node to its initial state."""
+ r"""Resets the node to its initial state."""
self._channel = TaskChannel()
self._running = False
diff --git a/camel/societies/workforce/task_channel.py b/camel/societies/workforce/task_channel.py
index cc881f131..d8cbfd77a 100644
--- a/camel/societies/workforce/task_channel.py
+++ b/camel/societies/workforce/task_channel.py
@@ -84,6 +84,9 @@ class TaskChannel:
self._task_dict: Dict[str, Packet] = {}
async def get_returned_task_by_publisher(self, publisher_id: str) -> Task:
+ r"""Get a task from the channel that has been returned by the
+ publisher.
+ """
async with self._condition:
while True:
for task_id in self._task_id_list:
@@ -96,6 +99,9 @@ class TaskChannel:
await self._condition.wait()
async def get_assigned_task_by_assignee(self, assignee_id: str) -> Task:
+ r"""Get a task from the channel that has been assigned to the
+ assignee.
+ """
async with self._condition:
while True:
for task_id in self._task_id_list:
@@ -147,12 +153,14 @@ class TaskChannel:
self._condition.notify_all()
async def remove_task(self, task_id: str) -> None:
+ r"""Remove a task from the channel."""
async with self._condition:
self._task_id_list.remove(task_id)
self._task_dict.pop(task_id)
self._condition.notify_all()
async def get_dependency_ids(self) -> List[str]:
+ r"""Get the IDs of all dependencies in the channel."""
async with self._condition:
dependency_ids = []
for task_id in self._task_id_list:
@@ -162,11 +170,13 @@ class TaskChannel:
return dependency_ids
async def get_task_by_id(self, task_id: str) -> Task:
+ r"""Get a task from the channel by its ID."""
async with self._condition:
if task_id not in self._task_id_list:
raise ValueError(f"Task {task_id} not found.")
return self._task_dict[task_id].task
async def get_channel_debug_info(self) -> str:
+ r"""Get the debug information of the channel."""
async with self._condition:
return str(self._task_dict) + '\n' + str(self._task_id_list)
diff --git a/camel/societies/workforce/utils.py b/camel/societies/workforce/utils.py
index e2148812a..cb04408e7 100644
--- a/camel/societies/workforce/utils.py
+++ b/camel/societies/workforce/utils.py
@@ -18,6 +18,8 @@ from pydantic import BaseModel, Field
class WorkerConf(BaseModel):
+ r"""The configuration of a worker."""
+
role: str = Field(
description="The role of the agent working in the work node."
)
@@ -31,6 +33,8 @@ class WorkerConf(BaseModel):
class TaskResult(BaseModel):
+ r"""The result of a task."""
+
content: str = Field(description="The result of the task.")
failed: bool = Field(
description="Flag indicating whether the task processing failed."
@@ -38,6 +42,8 @@ class TaskResult(BaseModel):
class TaskAssignResult(BaseModel):
+ r"""The result of task assignment."""
+
assignee_id: str = Field(
description="The ID of the workforce that is assigned to the task."
)
diff --git a/camel/societies/workforce/worker.py b/camel/societies/workforce/worker.py
index 7f49288f0..8ebd72b58 100644
--- a/camel/societies/workforce/worker.py
+++ b/camel/societies/workforce/worker.py
@@ -110,9 +110,11 @@ class Worker(BaseNode, ABC):
@check_if_running(False)
async def start(self):
+ r"""Start the worker."""
await self._listen_to_channel()
@check_if_running(True)
def stop(self):
+ r"""Stop the worker."""
self._running = False
return
diff --git a/camel/tasks/task.py b/camel/tasks/task.py
index 2521f5b0e..45c973f43 100644
--- a/camel/tasks/task.py
+++ b/camel/tasks/task.py
@@ -130,6 +130,11 @@ class Task(BaseModel):
self.set_state(TaskState.DONE)
def set_id(self, id: str):
+ r"""Set the id of the task.
+
+ Args:
+ id (str): The id of the task.
+ """
self.id = id
def set_state(self, state: TaskState):
@@ -147,10 +152,20 @@ class Task(BaseModel):
self.parent.set_state(state)
def add_subtask(self, task: "Task"):
+ r"""Add a subtask to the current task.
+
+ Args:
+ task (Task): The subtask to be added.
+ """
task.parent = self
self.subtasks.append(task)
def remove_subtask(self, id: str):
+ r"""Remove a subtask from the current task.
+
+ Args:
+ id (str): The id of the subtask to be removed.
+ """
self.subtasks = [task for task in self.subtasks if task.id != id]
def get_running_task(self) -> Optional["Task"]:
diff --git a/camel/terminators/base.py b/camel/terminators/base.py
index c20250e17..f1b8d08b2 100644
--- a/camel/terminators/base.py
+++ b/camel/terminators/base.py
@@ -18,6 +18,8 @@ from camel.messages import BaseMessage
class BaseTerminator(ABC):
+ r"""Base class for terminators."""
+
def __init__(self, *args, **kwargs) -> None:
self._terminated: bool = False
self._termination_reason: Optional[str] = None
@@ -32,6 +34,8 @@ class BaseTerminator(ABC):
class ResponseTerminator(BaseTerminator):
+ r"""A terminator that terminates the conversation based on the response."""
+
@abstractmethod
def is_terminated(
self, messages: List[BaseMessage]
diff --git a/camel/terminators/response_terminator.py b/camel/terminators/response_terminator.py
index 500e04d6a..f82da9550 100644
--- a/camel/terminators/response_terminator.py
+++ b/camel/terminators/response_terminator.py
@@ -122,6 +122,7 @@ class ResponseWordsTerminator(ResponseTerminator):
return self._terminated, self._termination_reason
def reset(self):
+ r"""Reset the terminator."""
self._terminated = False
self._termination_reason = None
self._word_count_dict = defaultdict(int)
diff --git a/camel/terminators/token_limit_terminator.py b/camel/terminators/token_limit_terminator.py
index 38b1d6ffd..7eaeaf2fd 100644
--- a/camel/terminators/token_limit_terminator.py
+++ b/camel/terminators/token_limit_terminator.py
@@ -53,5 +53,6 @@ class TokenLimitTerminator(BaseTerminator):
return self._terminated, self._termination_reason
def reset(self):
+ r"""Reset the terminator."""
self._terminated = False
self._termination_reason = None
diff --git a/camel/toolkits/base.py b/camel/toolkits/base.py
index e8e3e0d39..1396febe1 100644
--- a/camel/toolkits/base.py
+++ b/camel/toolkits/base.py
@@ -19,5 +19,14 @@ from camel.utils import AgentOpsMeta
class BaseToolkit(metaclass=AgentOpsMeta):
+ r"""Base class for toolkits."""
+
def get_tools(self) -> List[FunctionTool]:
+ r"""Returns a list of FunctionTool objects representing the
+ functions in the toolkit.
+
+ Returns:
+ List[FunctionTool]: A list of FunctionTool objects
+ representing the functions in the toolkit.
+ """
raise NotImplementedError("Subclasses must implement this method.")
diff --git a/camel/toolkits/function_tool.py b/camel/toolkits/function_tool.py
index 7237a5671..926de62cb 100644
--- a/camel/toolkits/function_tool.py
+++ b/camel/toolkits/function_tool.py
@@ -562,6 +562,8 @@ warnings.simplefilter('always', DeprecationWarning)
# Alias for backwards compatibility
class OpenAIFunction(FunctionTool):
+ r"""Alias for backwards compatibility."""
+
def __init__(self, *args, **kwargs):
PURPLE = '\033[95m'
RESET = '\033[0m'
diff --git a/camel/utils/commons.py b/camel/utils/commons.py
index 7ed5fee56..30c0b695a 100644
--- a/camel/utils/commons.py
+++ b/camel/utils/commons.py
@@ -550,8 +550,9 @@ class AgentOpsMeta(type):
return super().__new__(cls, name, bases, dct)
-# Mock trak agent decorator for AgentOps
def track_agent(*args, **kwargs):
+ r"""Mock track agent decorator for AgentOps."""
+
def noop(f):
return f
diff --git a/camel/utils/constants.py b/camel/utils/constants.py
index 659dd9968..e7d1aa233 100644
--- a/camel/utils/constants.py
+++ b/camel/utils/constants.py
@@ -14,6 +14,8 @@
class Constants:
+ r"""A class containing constants used in CAMEL."""
+
# This value defines the default size (both width and height) for images
# extracted from a video.
VIDEO_DEFAULT_IMAGE_SIZE = 768