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

fix: craw4ai inilization and humantoolkit docstring polish

Wendong806326cb669e
diff --git a/camel/societies/workforce/single_agent_worker.py b/camel/societies/workforce/single_agent_worker.py
index caa6af2b5..45c85ceff 100644
--- a/camel/societies/workforce/single_agent_worker.py
+++ b/camel/societies/workforce/single_agent_worker.py
@@ -43,8 +43,6 @@ class AgentPool:
(default: :obj:`10`)
auto_scale (bool): Whether to automatically scale the pool size.
(default: :obj:`True`)
- scale_factor (float): Factor by which to scale the pool when needed.
- (default: :obj:`1.5`)
idle_timeout (float): Time in seconds after which idle agents are
removed. (default: :obj:`180.0`)
"""
@@ -55,13 +53,11 @@ class AgentPool:
initial_size: int = 1,
max_size: int = 10,
auto_scale: bool = True,
- scale_factor: float = 1.5,
idle_timeout: float = 180.0, # 3 minutes
):
self.base_agent = base_agent
self.max_size = max_size
self.auto_scale = auto_scale
- self.scale_factor = scale_factor
self.idle_timeout = idle_timeout
# Pool management
@@ -332,7 +328,7 @@ class SingleAgentWorker(Worker):
# Store the actual token usage for this specific task
task.additional_info["token_usage"] = {"total_tokens": total_tokens}
- print(f"======\n{Fore.GREEN}Reply from {self}:{Fore.RESET}")
+ print(f"======\n{Fore.GREEN}Response from {self}:{Fore.RESET}")
try:
result_dict = json.loads(response.msg.content)
diff --git a/camel/toolkits/craw4ai_toolkit.py b/camel/toolkits/craw4ai_toolkit.py
index ab7ec841f..41221e5e2 100644
--- a/camel/toolkits/craw4ai_toolkit.py
+++ b/camel/toolkits/craw4ai_toolkit.py
@@ -31,6 +31,16 @@ class Crawl4AIToolkit(BaseToolkit):
timeout: Optional[float] = None,
):
super().__init__(timeout=timeout)
+ self._client = None
+
+ async def _get_client(self):
+ r"""Get or create the AsyncWebCrawler client."""
+ if self._client is None:
+ from crawl4ai import AsyncWebCrawler
+
+ self._client = AsyncWebCrawler()
+ await self._client.__aenter__()
+ return self._client
async def scrape(self, url: str) -> str:
r"""Scrapes a webpage and returns its content.
@@ -47,19 +57,29 @@ class Crawl4AIToolkit(BaseToolkit):
str: The scraped content of the webpage as a string. If the
scraping fails, it will return an error message.
"""
- from crawl4ai import AsyncWebCrawler, CrawlerRunConfig
+ from crawl4ai import CrawlerRunConfig
try:
- async with AsyncWebCrawler() as client:
- config = CrawlerRunConfig(
- only_text=True,
- )
- content = await client.arun(url, crawler_config=config)
- return str(content.markdown) if content.markdown else ""
+ client = await self._get_client()
+ config = CrawlerRunConfig(
+ only_text=True,
+ )
+ content = await client.arun(url, crawler_config=config)
+ return str(content.markdown) if content.markdown else ""
except Exception as e:
logger.error(f"Error scraping {url}: {e}")
return f"Error scraping {url}: {e}"
+ async def __aenter__(self):
+ """Async context manager entry."""
+ return self
+
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
+ """Async context manager exit - cleanup the client."""
+ if self._client is not None:
+ await self._client.__aexit__(exc_type, exc_val, exc_tb)
+ self._client = None
+
def get_tools(self) -> List[FunctionTool]:
r"""Returns a list of FunctionTool objects representing the
functions in the toolkit.
diff --git a/camel/toolkits/human_toolkit.py b/camel/toolkits/human_toolkit.py
index ed3b9b32f..4c5a59c62 100644
--- a/camel/toolkits/human_toolkit.py
+++ b/camel/toolkits/human_toolkit.py
@@ -22,7 +22,12 @@ logger = logging.getLogger(__name__)
class HumanToolkit(BaseToolkit):
- r"""A class representing a toolkit for human interaction."""
+ r"""A class representing a toolkit for human interaction.
+
+ Note:
+ This toolkit should be called to send a tidy message to the user to
+ keep them informed.
+ """
def ask_human_via_console(self, question: str) -> str:
r"""Use this tool to ask a question to the user when you are stuck,
@@ -48,21 +53,21 @@ class HumanToolkit(BaseToolkit):
return reply
def send_message_to_user(self, message: str) -> None:
- r"""Use this tool to send a message to the user to keep them
- informed about your progress, decisions, or actions.
- This is a one-way communication channel from you to the user and does
- not require a response. You should use it to:
- - Announce what you are about to do
- (e.g., "I will now search for papers on GUI Agents.")
- - Report the result of an action
- (e.g., "I have found 15 relevant papers.")
- - State a decision
- (e.g., "I will now analyze the top 10 papers.")
- - Inform the user about your current state if you are performing a
- task.
+ r"""Use this tool to send a tidy message to the user in one short
+ sentence.
+
+ This one-way tool keeps the user informed about your progress,
+ decisions, or actions. It does not require a response.
+ You should use it to:
+ - Announce what you are about to do (e.g., "I will now search for
+ papers on GUI Agents.").
+ - Report the result of an action (e.g., "I have found 15 relevant
+ papers.").
+ - State a decision (e.g., "I will now analyze the top 10 papers.").
+ - Give a status update during a long-running task.
Args:
- message (str): The message to send to the user.
+ message (str): The tidy and informative message for the user.
"""
print(f"\nAgent Message:\n{message}")
logger.info(f"\nAgent Message:\n{message}")
diff --git a/examples/workforce/eigent.py b/examples/workforce/eigent.py
index 0d72949e9..3563c6087 100644
--- a/examples/workforce/eigent.py
+++ b/examples/workforce/eigent.py
@@ -63,8 +63,9 @@ def developer_agent_factory(
system_message = """You are a skilled coding assistant with DIRECT CODE
EXECUTION CAPABILITIES. You MUST use the `send_message_to_user` tool to
- inform the user of every decision and action you take. This is a mandatory
- part of your workflow.
+ inform the user of every decision and action you take. Your message must
+ be tidy and in one short sentence. This is a mandatory part of your
+ workflow.
Your capabilities include:
- WRITE AND EXECUTE code in real-time to solve tasks
@@ -120,7 +121,8 @@ def search_agent_factory(
information to solve the given task.
You MUST use the `send_message_to_user` tool to inform the user of every
- decision and action you take. This is a mandatory part of your workflow.
+ decision and action you take. Your message must be tidy and in one short
+ sentence. This is a mandatory part of your workflow.
Keep in mind that:
- For each decision you make and action you take, you must send a message
@@ -201,7 +203,8 @@ def document_agent_factory(
system_message = """You are a Document Processing Assistant specialized in
creating, modifying, and managing various document formats. You MUST use
the `send_message_to_user` tool to inform the user of every decision and
- action you take. This is a mandatory part of your workflow.
+ action you take. Your message must be tidy and in one short sentence.
+ This is a mandatory part of your workflow.
Your capabilities include:
@@ -278,7 +281,8 @@ def multi_modal_agent_factory(model: BaseModelBackend, task_id: str):
system_message = """You are a Multi-Modal Processing Assistant specialized
in analyzing and generating various types of media content. You MUST use
the `send_message_to_user` tool to inform the user of every decision and
- action you take. This is a mandatory part of your workflow.
+ action you take. Your message must be tidy and in one short sentence.
+ This is a mandatory part of your workflow.
Your capabilities include:
@@ -332,8 +336,8 @@ def social_medium_agent_factory(model: BaseModelBackend, task_id: str):
content="""
You are a Social Media Management Assistant with comprehensive capabilities
across multiple platforms. You MUST use the `send_message_to_user` tool to
-inform the user of every decision and action you take. This is a mandatory
-part of your workflow.
+inform the user of every decision and action you take. Your message must be
+tidy and in one short sentence. This is a mandatory part of your workflow.
Your integrated toolkits enable you to:
@@ -423,8 +427,9 @@ async def main():
coordinator_agent = ChatAgent(
"You are a helpful coordinator. You MUST use the "
"`send_message_to_user` tool to inform the user of every "
- "decision and action you take. This is a mandatory part of your "
- "workflow.",
+ "decision and action you take. Your message must be tidy "
+ "and in one short sentence. This is a mandatory part of "
+ "your workflow.",
model=model_backend_reason,
tools=[
*HumanToolkit().get_tools(),
@@ -433,8 +438,9 @@ async def main():
task_agent = ChatAgent(
"You are a helpful task planner. You MUST use the "
"`send_message_to_user` tool to inform the user of every "
- "decision and action you take. This is a mandatory part of your "
- "workflow.",
+ "decision and action you take. Your message must be tidy "
+ "and in one short sentence. This is a mandatory part of "
+ "your workflow.",
model=model_backend_reason,
tools=[
*HumanToolkit().get_tools(),
@@ -443,8 +449,8 @@ async def main():
new_worker_agent = ChatAgent(
"You are a helpful worker. You MUST use the "
"`send_message_to_user` tool to inform the user of every "
- "decision and action you take. This is a mandatory part of your "
- "workflow.",
+ "decision and action you take. Your message must be tidy and in "
+ "one short sentence. This is a mandatory part of your workflow.",
model=model_backend,
tools=[
*HumanToolkit().get_tools(),