🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
feat: add note taking toolkit, polish toolkit docstring and prompt (#2792)
Wendong-Fan28b083339da6
diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.pyindex 3fc1b6cf6..8d4c033d6 100644--- a/camel/toolkits/__init__.py+++ b/camel/toolkits/__init__.py@@ -82,6 +82,7 @@ from .edgeone_pages_mcp_toolkit import EdgeOnePagesMCPToolkitfrom .google_drive_mcp_toolkit import GoogleDriveMCPToolkitfrom .craw4ai_toolkit import Crawl4AIToolkitfrom .markitdown_toolkit import MarkItDownToolkit+from .note_taking_toolkit import NoteTakingToolkit__all__ = ['BaseToolkit',@@ -152,4 +153,5 @@ __all__ = ['GoogleDriveMCPToolkit','Crawl4AIToolkit','MarkItDownToolkit',+ 'NoteTakingToolkit',]diff --git a/camel/toolkits/file_write_toolkit.py b/camel/toolkits/file_write_toolkit.pyindex 2b6641acc..5389aea6d 100644--- a/camel/toolkits/file_write_toolkit.py+++ b/camel/toolkits/file_write_toolkit.py@@ -160,9 +160,9 @@ class FileWriteToolkit(BaseToolkit):file_path (Path): The target file path.title (str): The title of the document.content (str): The text content to write.- use_latex (bool): Whether to use LaTeX for rendering. (requires- LaTeX toolchain). If False, uses PyMuPDF for simpler PDF- generation. (default: :obj:`False`)+ use_latex (bool): Whether to use LaTeX for rendering. Only+ Recommended for documents with mathematical formulas or+ complex typesetting needs. (default: :obj:`False`)"""# TODO: table generation need to be improvedif use_latex:@@ -439,9 +439,9 @@ class FileWriteToolkit(BaseToolkit):supplied, it is resolved to self.output_dir.encoding (Optional[str]): The character encoding to use. (default::obj: `None`)- use_latex (bool): For PDF files, whether to use LaTeX rendering- (True) or simple FPDF rendering (False). (default: :obj:- `False`)+ use_latex (bool): For PDF files, whether to use LaTeX rendering.+ Only recommended for documents with mathematical formulas or+ complex typesetting needs. (default: :obj:`False`)Returns:str: A message indicating success or error details.diff --git a/camel/toolkits/hybrid_browser_toolkit/hybrid_browser_toolkit.py b/camel/toolkits/hybrid_browser_toolkit/hybrid_browser_toolkit.pyindex c27860bdf..f1407c553 100644--- a/camel/toolkits/hybrid_browser_toolkit/hybrid_browser_toolkit.py+++ b/camel/toolkits/hybrid_browser_toolkit/hybrid_browser_toolkit.py@@ -56,6 +56,7 @@ class HybridBrowserToolkit(BaseToolkit):"visit_page","click","type",+ "enter",]# All available tools@@ -509,17 +510,19 @@ class HybridBrowserToolkit(BaseToolkit):# Public API Methodsasync def open_browser(- self, start_url: Optional[str] = None+ self, start_url: Optional[str] = "https://search.brave.com/") -> Dict[str, str]:r"""Launches a new browser session, making it ready for web automation.This method initializes the underlying browser instance. If a- `start_url` is provided, it will also navigate to that URL.+ `start_url` is provided, it will also navigate to that URL. If you+ don't have a specific URL to start with, you can use a search engine+ like 'https://search.brave.com/'.Args:start_url (Optional[str]): The initial URL to navigate to after thebrowser is launched. If not provided, the browser will start- with a blank page.+ with a blank page. (default: :obj:`https://search.brave.com/`)Returns:Dict[str, str]: A dictionary containing:@@ -590,6 +593,9 @@ class HybridBrowserToolkit(BaseToolkit):"snapshot": "",}+ if '://' not in url:+ url = f'https://{url}'+logger.info(f"Navigating to URL: {url}")# Navigate to pagediff --git a/camel/toolkits/note_taking_toolkit.py b/camel/toolkits/note_taking_toolkit.pynew file mode 100644index 000000000..61c33d6a3--- /dev/null+++ b/camel/toolkits/note_taking_toolkit.py@@ -0,0 +1,90 @@+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+from pathlib import Path+from typing import List, Optional++from camel.toolkits.base import BaseToolkit+from camel.toolkits.function_tool import FunctionTool+++class NoteTakingToolkit(BaseToolkit):+ r"""A toolkit for taking notes in a Markdown file.++ This toolkit allows an agent to create, append to, and update a specific+ Markdown file for note-taking purposes.+ """++ def __init__(+ self,+ note_file_path: str = "notes/notes.md",+ timeout: Optional[float] = None,+ ) -> None:+ r"""Initialize the NoteTakingToolkit.++ Args:+ note_file_path (str): The path to the note file.+ (default: :obj:`notes/notes.md`)+ timeout (Optional[float]): The timeout for the toolkit.+ """+ super().__init__(timeout=timeout)+ self.note_file_path = Path(note_file_path)+ self.note_file_path.parent.mkdir(parents=True, exist_ok=True)++ def take_note(self, content: str, update: bool = False) -> str:+ r"""Takes a note and saves it to the note file.++ Args:+ content (str): The content of the note to be saved.+ update (bool): If True, the existing note file will be+ overwritten with the new content. If False, the new content+ will be appended to the end of the file.+ (default: :obj:`False`)++ Returns:+ str: A message indicating the result of the operation.+ """+ mode = "w" if update else "a"+ try:+ with self.note_file_path.open(mode, encoding="utf-8") as f:+ f.write(content + "\n")+ action = "updated" if update else "appended to"+ return f"Note successfully {action} in {self.note_file_path}."+ except Exception as e:+ return f"Error taking note: {e}"++ def read_note(self) -> str:+ r"""Reads the content of the note file.++ Returns:+ str: The content of the note file, or an error message if the+ file cannot be read.+ """+ try:+ if not self.note_file_path.exists():+ return "Note file does not exist yet."+ return self.note_file_path.read_text(encoding="utf-8")+ except Exception as e:+ return f"Error reading note: {e}"++ def get_tools(self) -> List[FunctionTool]:+ r"""Return a list of FunctionTool objects representing the functions+ in the toolkit.++ Returns:+ List[FunctionTool]: A list of FunctionTool objects.+ """+ return [+ FunctionTool(self.take_note),+ FunctionTool(self.read_note),+ ]diff --git a/examples/workforce/eigent.py b/examples/workforce/eigent.pyindex 3691b2fb0..2a37406a2 100644--- a/examples/workforce/eigent.py+++ b/examples/workforce/eigent.py@@ -27,13 +27,13 @@ from camel.toolkits import (EdgeOnePagesMCPToolkit,ExcelToolkit,FileWriteToolkit,- FunctionTool,# GoogleDriveMCPToolkit,HumanToolkit,HybridBrowserToolkit,ImageAnalysisToolkit,LinkedInToolkit,MarkItDownToolkit,+ NoteTakingToolkit,NotionToolkit,OpenAIImageToolkit,PPTXToolkit,@@ -137,13 +137,14 @@ def search_agent_factory("""tools = [# FunctionTool(SearchToolkit().search_wiki),- FunctionTool(SearchToolkit().search_exa),+ SearchToolkit().search_exa,# FunctionTool(SearchToolkit().search_bing),# FunctionTool(SearchToolkit().search_baidu),*HybridBrowserToolkit(headless=False).get_tools(),*TerminalToolkit().get_tools(),send_message_to_user,HumanToolkit().ask_human_via_console,+ NoteTakingToolkit().take_note,*Crawl4AIToolkit().get_tools(),]@@ -156,53 +157,56 @@ def search_agent_factory(and a one-sentence description. This is a mandatory part of yourworkflow.- Keep in mind that:+ ### Core Principles- For each decision you make and action you take, you must send a messageto the user to keep them informed.- Do not be overly confident in your own knowledge. Searching can provide- a broader perspective and help validate existing knowledge.+ a broader perspective and help validate existing knowledge.- If one way fails to provide an answer, try other ways or methods. Theanswer does exist.- - When encountering verification challenges (like login, CAPTCHAs or robot- checks), you MUST request help using the human toolkit.++ ### Note Taking+ - As you find information, you MUST use the `take_note` tool to record+ your findings in a structured way.+ - Append new information to the notes. Do not overwrite the note file+ unless you are summarizing or restructuring the content.+ - Your notes will be used by the Document Agent to create the final+ report, so make them clear, concise, and well-organized. Include+ headings, details, and any relevant URLs or sources.++ ### Web Search Strategy+ - When solving tasks that require web searches, check Wikipedia first+ before exploring other websites.+ - If a question is complex, your search query should be concise and focus+ on finding official sources. For example, to answer "What is the maximum+ length in meters of #9 in the first National Geographic short on YouTube+ that was ever released according to the Monterey Bay Aquarium website?",+ your first search term should be coarse-grained like "National+ Geographic YouTube" to find the official channel first, then narrow down+ your search.- If the search snippet is unhelpful but the URL comes from an- authoritative source, try visit the website for more details.- - For the page you have visited, you should check the subpages of the page- to see if it can provide more information to solve the task.+ authoritative source, try visiting the website for more details.- When looking for specific numerical values (e.g., dollar amounts),- prioritize reliable sources and avoid relying only on search snippets.- - When solving tasks that require web searches, check Wikipedia first- before exploring other websites.- - You can also simulate browser actions to get more information or verify- the information you have found.- - Browser simulation is also helpful for finding target URLs. Browser- simulation operations do not necessarily need to find specific answers,- but can also help find web page URLs that contain answers (usually- difficult to find through simple web searches). You can find the answer to- the question by performing subsequent operations on the URL, such as- extracting the content of the webpage.- - Do not solely rely on browser simulation to find the- answer, you should combine search tools, scraper tools and browser- simulation to comprehensively process web page information. Some content- may need to do browser simulation to get.- - In your response, you should mention the urls you have visited and+ prioritize reliable sources and avoid relying only on search snippets.++ ### Browser Interaction+ - When using `open_browser` or `visit_page` without a specific URL in+ mind, start from a search engine like Brave Search+ (https://search.brave.com) instead of trying to guess the URL.+ - You can simulate browser actions to get more information or verify what+ you have found. This is also helpful for finding target URLs that are+ hard to find with simple web searches.+ - After visiting a page, check its subpages for more relevant+ information.+ - Do not rely solely on browser simulation. Combine search, scraper, and+ browser tools to process web page information comprehensively. Some+ content may require browser simulation to access.+ - In your response, you should mention the URLs you have visited andprocessed.-Here are some tips that help you perform web search:-- Never add too many keywords in your search query! Some detailed results need- to perform browser interaction to get, not using search toolkit.-- If the question is complex, search results typically do not provide precise- answers. It is not likely to find the answer directly using search toolkit- only, the search query should be concise and focuses on finding official- sources rather than direct answers.- For example, as for the question "What is the maximum length in meters of- #9 in the first National Geographic short on YouTube that was ever- released according to the Monterey Bay Aquarium website?", your first- search term must be coarse-grained like "National Geographic YouTube" to- find the youtube website first, and then try other fine-grained search- terms step-by-step to find more urls.-- The results you return do not have to directly answer the original question,- you only need to collect relevant information.+ ### Handling Obstacles+ - When encountering verification challenges (like login, CAPTCHAs or+ robot checks), you MUST request help using the human toolkit."""return ChatAgent(@@ -231,6 +235,7 @@ def document_agent_factory(HumanToolkit().ask_human_via_console,*MarkItDownToolkit().get_tools(),*ExcelToolkit().get_tools(),+ NoteTakingToolkit().read_note,]system_message = """You are a Document Processing Assistant specialized in@@ -241,7 +246,13 @@ def document_agent_factory(Your capabilities include:- 1. Document Creation & Editing:+ 1. Information Gathering:+ - Before creating any document, you MUST use the `read_note` tool to+ get all the information gathered by the Search Agent.+ - The notes contain all the raw data, findings, and sources you need+ to complete your work.++ 2. Document Creation & Editing:- Create and write to various file formats including Markdown (.md),Word documents (.docx), PDFs, CSV files, JSON, YAML, and HTML- Apply formatting options including custom encoding, font styles, and@@ -250,7 +261,7 @@ def document_agent_factory(- Support for mathematical expressions in PDF documents through LaTeXrendering- 2. PowerPoint Presentation Creation:+ 3. PowerPoint Presentation Creation:- Create professional PowerPoint presentations with title slides andcontent slides- Format text with bold and italic styling@@ -259,7 +270,7 @@ def document_agent_factory(- Create tables with headers and rows of data- Support for custom templates and slide layouts- 3. Excel Spreadsheet Management:+ 4. Excel Spreadsheet Management:- Extract and analyze content from Excel files (.xlsx, .xls, .csv)with detailed cell information and markdown formatting- Create new Excel workbooks from scratch with multiple sheets@@ -272,7 +283,7 @@ def document_agent_factory(- Handle complex data structures with proper formatting and validation- Support for both programmatic data entry and manual cell updates- 4. Human Interaction:+ 5. Human Interaction:- Ask questions to users and receive their responses- Send informative messages to users without requiring responses@@ -542,11 +553,13 @@ async def main():human_task = Task(content=("""-I want to read papers about GUI Agent. Please help me find-ten papers, check the detailed content of the papers and help-me write a comparison report, then create a nice slides(pptx)-to introduce the latest research progress of GUI Agent. The-slides should be very comprehensive and professional.+Analyze the UK healthcare industry to support the planning of my next company.+Provide a comprehensive market overview, including current trends, growth+projections, and relevant regulations. Identify the top 5-10 major competitors+in the space, including their names, website URLs, estimated market size or+share, core services or products, key strengths, and notable weaknesses. Also+highlight any significant opportunities, gaps, or underserved segments within+the market. Present all findings in a well-structured, professional PDF report."""),id='0',diff --git a/test/toolkits/test_note_taking_toolkit.py b/test/toolkits/test_note_taking_toolkit.pynew file mode 100644index 000000000..c453be425--- /dev/null+++ b/test/toolkits/test_note_taking_toolkit.py@@ -0,0 +1,76 @@+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+from pathlib import Path++import pytest++from camel.toolkits import NoteTakingToolkit+++def note_taking_toolkit():+ # Create a toolkit with a temporary note file+ return NoteTakingToolkit(note_file_path="test_notes.md")+++def test_take_note_append(note_taking_toolkit):+ # Test appending a note+ note_file = Path("test_notes.md")+ if note_file.exists():+ note_file.unlink()++ result = note_taking_toolkit.take_note("First note.")+ assert "appended" in result+ assert note_file.read_text() == "First note.\n"++ result = note_taking_toolkit.take_note("Second note.")+ assert "appended" in result+ assert note_file.read_text() == "First note.\nSecond note.\n"++ # Clean up the test file+ if note_file.exists():+ note_file.unlink()+++def test_take_note_update(note_taking_toolkit):+ # Test updating a note+ note_file = Path("test_notes.md")+ if note_file.exists():+ note_file.unlink()++ note_taking_toolkit.take_note("Initial content.")+ result = note_taking_toolkit.take_note("Updated content.", update=True)+ assert "updated" in result+ assert note_file.read_text() == "Updated content.\n"++ # Clean up the test file+ if note_file.exists():+ note_file.unlink()+++def test_read_note(note_taking_toolkit):+ # Test reading a note+ note_file = Path("test_notes.md")+ if note_file.exists():+ note_file.unlink()++ # Test reading non-existent file+ assert "does not exist" in note_taking_toolkit.read_note()++ note_taking_toolkit.take_note("Hello, world!")+ assert note_taking_toolkit.read_note() == "Hello, world!\n"++ # Clean up the test file+ if note_file.exists():+ note_file.unlink()