🐫 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: Support browser toolkit with pre-defined dynamic channel (#1937)
Kenny Dizi5b6914accd6f
diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.pyindex 7da68879b..82bd96295 100644--- a/camel/toolkits/__init__.py+++ b/camel/toolkits/__init__.py@@ -56,7 +56,7 @@ from .excel_toolkit import ExcelToolkitfrom .video_analysis_toolkit import VideoAnalysisToolkitfrom .image_analysis_toolkit import ImageAnalysisToolkitfrom .mcp_toolkit import MCPToolkit-from .browser_toolkit import BrowserToolkit+from .browser_toolkit import BrowserToolkit, ChromiumChannelsfrom .file_write_toolkit import FileWriteToolkitfrom .terminal_toolkit import TerminalToolkitfrom .pubmed_toolkit import PubMedToolkit@@ -106,6 +106,7 @@ __all__ = ['VideoAnalysisToolkit','ImageAnalysisToolkit','BrowserToolkit',+ 'ChromiumChannels','FileWriteToolkit','TerminalToolkit','PubMedToolkit',diff --git a/camel/toolkits/browser_toolkit.py b/camel/toolkits/browser_toolkit.pyindex 5fd653ed6..cb9b485e5 100644--- a/camel/toolkits/browser_toolkit.py+++ b/camel/toolkits/browser_toolkit.py@@ -21,6 +21,7 @@ import reimport shutilimport timefrom copy import deepcopy+from enum import Enumfrom typing import (TYPE_CHECKING,Any,@@ -51,37 +52,37 @@ logger = get_logger(__name__)TOP_NO_LABEL_ZONE = 20AVAILABLE_ACTIONS_PROMPT = """-1. `fill_input_id(identifier: Union[str, int], text: str)`: Fill an input+1. `fill_input_id(identifier: Union[str, int], text: str)`: Fill an inputfield (e.g. search box) with the given text and press Enter.2. `click_id(identifier: Union[str, int])`: Click an element with the given ID.-3. `hover_id(identifier: Union[str, int])`: Hover over an element with the+3. `hover_id(identifier: Union[str, int])`: Hover over an element with thegiven ID.-4. `download_file_id(identifier: Union[str, int])`: Download a file with the-given ID. It returns the path to the downloaded file. If the file is-successfully downloaded, you can stop the simulation and report the path to+4. `download_file_id(identifier: Union[str, int])`: Download a file with the+given ID. It returns the path to the downloaded file. If the file is+successfully downloaded, you can stop the simulation and report the path tothe downloaded file for further processing.5. `scroll_to_bottom()`: Scroll to the bottom of the page.6. `scroll_to_top()`: Scroll to the top of the page.-7. `scroll_up()`: Scroll up the page. It is suitable when you want to see the+7. `scroll_up()`: Scroll up the page. It is suitable when you want to see theelements above the current viewport.-8. `scroll_down()`: Scroll down the page. It is suitable when you want to see-the elements below the current viewport. If the webpage does not change, It+8. `scroll_down()`: Scroll down the page. It is suitable when you want to see+the elements below the current viewport. If the webpage does not change, Itmeans that the webpage has scrolled to the bottom.-9. `back()`: Navigate back to the previous page. This is useful when you want+9. `back()`: Navigate back to the previous page. This is useful when you wantto go back to the previous page, as current page is not useful.-10. `stop()`: Stop the action process, because the task is completed or failed-(impossible to find the answer). In this situation, you should provide your+10. `stop()`: Stop the action process, because the task is completed or failed+(impossible to find the answer). In this situation, you should provide youranswer in your output.11. `get_url()`: Get the current URL of the current page.-12. `find_text_on_page(search_text: str)`: Find the next given text on the-current whole page, and scroll the page to the targeted text. It is equivalent-to pressing Ctrl + F and searching for the text, and is powerful when you want+12. `find_text_on_page(search_text: str)`: Find the next given text on the+current whole page, and scroll the page to the targeted text. It is equivalent+to pressing Ctrl + F and searching for the text, and is powerful when you wantto fast-check whether the current page contains some specific text.13. `visit_page(url: str)`: Go to the specific url page.-14. `click_blank_area()`: Click a blank area of the page to unfocus the-current element. It is useful when you have clicked an element but it cannot+14. `click_blank_area()`: Click a blank area of the page to unfocus the+current element. It is useful when you have clicked an element but it cannotunfocus itself (e.g. Menu bar) to automatically render the updated webpage.-15. `ask_question_about_video(question: str)`: Ask a question about the+15. `ask_question_about_video(question: str)`: Ask a question about thecurrent webpage which contains video, e.g. youtube websites."""@@ -126,6 +127,16 @@ class InteractiveRegion(TypedDict):rects: List[DOMRectangle]+class ChromiumChannels(Enum):+ """+ Enum for the accepted browser channels.+ """++ CHROME = "chrome"+ MSEDGE = "msedge"+ CHROMIUM = "chromium"++def _get_str(d: Any, k: str) -> str:r"""Safely retrieve a string value from a dictionary."""if k not in d:@@ -424,8 +435,13 @@ def _get_random_color(identifier: int) -> Tuple[int, int, int, int]:class BaseBrowser:- def __init__(self, headless=True, cache_dir: Optional[str] = None):- r"""Initialize the WebBrowserToolkit instance.+ def __init__(+ self,+ headless=True,+ cache_dir: Optional[str] = None,+ channel: ChromiumChannels = ChromiumChannels.CHROMIUM,+ ):+ r"""Initialize the WebBrowser instance.Args:headless (bool): Whether to run the browser in headless mode.@@ -438,9 +454,10 @@ class BaseBrowser:sync_playwright,)- self._ensure_browser_installed()self.history: list = []self.headless = headless+ self.channel = channel.value+ self._ensure_browser_installed()self.playwright = sync_playwright().start()self.page_history: list = [] # stores the history of visited pages@@ -464,7 +481,9 @@ class BaseBrowser:def init(self) -> None:r"""Initialize the browser."""# Launch the browser, if headless is False, the browser will display- self.browser = self.playwright.chromium.launch(headless=self.headless)+ self.browser = self.playwright.chromium.launch(+ headless=self.headless, channel=self.channel+ )# Create a new contextself.context = self.browser.new_context(accept_downloads=True)# Create a new page@@ -925,7 +944,7 @@ class BaseBrowser:from playwright.sync_api import sync_playwrightwith sync_playwright() as p:- browser = p.chromium.launch()+ browser = p.chromium.launch(channel=self.channel)browser.close()except Exception:logger.info("Installing Chromium browser...")@@ -936,7 +955,7 @@ class BaseBrowser:"-m","playwright","install",- "chromium",+ self.channel,],check=True,capture_output=True,@@ -948,7 +967,7 @@ class BaseBrowser:"-m","playwright","install-deps",- "chromium",+ self.channel,],check=True,capture_output=True,@@ -969,6 +988,7 @@ class BrowserToolkit(BaseToolkit):self,headless: bool = False,cache_dir: Optional[str] = None,+ channel: ChromiumChannels = ChromiumChannels.CHROMIUM,history_window: int = 5,web_agent_model: Optional[BaseModelBackend] = None,planning_agent_model: Optional[BaseModelBackend] = None,@@ -987,7 +1007,11 @@ class BrowserToolkit(BaseToolkit):backend for the planning agent."""- self.browser = BaseBrowser(headless=headless, cache_dir=cache_dir)+ self.browser = BaseBrowser(+ headless=headless, cache_dir=cache_dir, channel=channel+ )+ # This needs to be called explicitly+ self.browser.init()self.history_window = history_windowself.web_agent_model = web_agent_model@@ -1026,7 +1050,7 @@ class BrowserToolkit(BaseToolkit):system_prompt = """You are a helpful web agent that can assist users in browsing the web.-Given a high-level task, you can leverage predefined browser tools to help+Given a high-level task, you can leverage predefined browser tools to helpusers achieve their goals."""@@ -1037,7 +1061,7 @@ users achieve their goals.)planning_system_prompt = """-You are a helpful planning agent that can assist users in planning complex+You are a helpful planning agent that can assist users in planning complextasks which need multi-step browser interaction."""@@ -1058,17 +1082,17 @@ tasks which need multi-step browser interaction.if detailed_plan is not None:detailed_plan_prompt = f"""-Here is a plan about how to solve the task step-by-step which you must follow:+Here is a plan about how to solve the task step-by-step which you must follow:<detailed_plan>{detailed_plan}<detailed_plan>"""observe_prompt = f"""-Please act as a web agent to help me complete the following high-level task:+Please act as a web agent to help me complete the following high-level task:<task>{task_prompt}</task>-Now, I have made screenshot (only the current viewport, not the full webpage)-based on the current browser state, and marked interactive elements in the+Now, I have made screenshot (only the current viewport, not the full webpage)+based on the current browser state, and marked interactive elements in thewebpage.-Please carefully examine the requirements of the task, and current state of+Please carefully examine the requirements of the task, and current state ofthe browser, and provide the next appropriate action to take.{detailed_plan_prompt}@@ -1082,14 +1106,14 @@ Here are the latest {self.history_window} trajectory (at most) you have taken:</history>Your output should be in json format, including the following fields:-- `observation`: The detailed image description about the current viewport. Do-not over-confident about the correctness of the history actions. You should-always check the current viewport to make sure the correctness of the next+- `observation`: The detailed image description about the current viewport. Do+not over-confident about the correctness of the history actions. You should+always check the current viewport to make sure the correctness of the nextaction.-- `reasoning`: The reasoning about the next action you want to take, and the-possible obstacles you may encounter, and how to solve them. Do not forget to+- `reasoning`: The reasoning about the next action you want to take, and the+possible obstacles you may encounter, and how to solve them. Do not forget tocheck the history actions to avoid the same mistakes.-- `action_code`: The action code you want to take. It is only one step action+- `action_code`: The action code you want to take. It is only one step actioncode, without any other texts (such as annotation)Here is two example of the output:@@ -1108,37 +1132,37 @@ Here is two example of the output:Here are some tips for you:- Never forget the overall question: **{task_prompt}**-- Maybe after a certain operation (e.g. click_id), the page content has not-changed. You can check whether the action step is successful by looking at the-`success` of the action step in the history. If successful, it means that the+- Maybe after a certain operation (e.g. click_id), the page content has not+changed. You can check whether the action step is successful by looking at the+`success` of the action step in the history. If successful, it means that thepage content is indeed the same after the click. You need to try other methods.-- If using one way to solve the problem is not successful, try other ways.+- If using one way to solve the problem is not successful, try other ways.Make sure your provided ID is correct!-- Some cases are very complex and need to be achieve by an iterative process.-You can use the `back()` function to go back to the previous page to try other+- Some cases are very complex and need to be achieve by an iterative process.+You can use the `back()` function to go back to the previous page to try othermethods.-- There are many links on the page, which may be useful for solving the-problem. You can use the `click_id()` function to click on the link to see if+- There are many links on the page, which may be useful for solving the+problem. You can use the `click_id()` function to click on the link to see ifit is useful.-- Always keep in mind that your action must be based on the ID shown in the+- Always keep in mind that your action must be based on the ID shown in thecurrent image or viewport, not the ID shown in the history.-- Do not use `stop()` lightly. Always remind yourself that the image only-shows a part of the full page. If you cannot find the answer, try to use-functions like `scroll_up()` and `scroll_down()` to check the full content of-the webpage before doing anything else, because the answer or next key step+- Do not use `stop()` lightly. Always remind yourself that the image only+shows a part of the full page. If you cannot find the answer, try to use+functions like `scroll_up()` and `scroll_down()` to check the full content of+the webpage before doing anything else, because the answer or next key stepmay be hidden in the content below.-- If the webpage needs human verification, you must avoid processing it.+- If the webpage needs human verification, you must avoid processing it.Please use `back()` to go back to the previous page, and try other ways.-- If you have tried everything and still cannot resolve the issue, please stop+- If you have tried everything and still cannot resolve the issue, please stopthe simulation, and report issues you have encountered.-- Check the history actions carefully, detect whether you have repeatedly made+- Check the history actions carefully, detect whether you have repeatedly madethe same actions or not.-- When dealing with wikipedia revision history related tasks, you need to-think about the solution flexibly. First, adjust the browsing history-displayed on a single page to the maximum, and then make use of the-find_text_on_page function. This is extremely useful which can quickly locate+- When dealing with wikipedia revision history related tasks, you need to+think about the solution flexibly. First, adjust the browsing history+displayed on a single page to the maximum, and then make use of the+find_text_on_page function. This is extremely useful which can quickly locatethe text you want to find and skip massive amount of useless information.-- Flexibly use interactive elements like slide down selection bar to filter+- Flexibly use interactive elements like slide down selection bar to filterout the information you need. Sometimes they are extremely useful.```"""diff --git a/examples/toolkits/web_toolkit.py b/examples/toolkits/web_toolkit.pyindex 606babdaa..23d62b7ea 100644--- a/examples/toolkits/web_toolkit.py+++ b/examples/toolkits/web_toolkit.py@@ -16,7 +16,7 @@from camel.agents import ChatAgentfrom camel.configs import ChatGPTConfigfrom camel.models import ModelFactory-from camel.toolkits import BrowserToolkit+from camel.toolkits import BrowserToolkit, ChromiumChannelsfrom camel.types import ModelPlatformType, ModelTypemodel = ModelFactory.create(@@ -47,6 +47,7 @@ web_toolkit = BrowserToolkit(headless=False,web_agent_model=web_agent_model,planning_agent_model=planning_agent_model,+ channel=ChromiumChannels.CHROMIUM,)agent = ChatAgent(diff --git a/test/toolkits/test_browser_toolkit.py b/test/toolkits/test_browser_toolkit.pynew file mode 100644index 000000000..b0e30c510--- /dev/null+++ b/test/toolkits/test_browser_toolkit.py@@ -0,0 +1,175 @@+# ========= 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. =========+import io+import os+from unittest.mock import MagicMock, patch++import pytest+from PIL import Image++from camel.toolkits.browser_toolkit import (+ BaseBrowser,+ BrowserToolkit,+ ChromiumChannels,+)++TEST_URL = "https://example.com"++[email protected](scope="function")+def base_browser_fixture():+ with patch('playwright.sync_api.sync_playwright'):+ browser = BaseBrowser(headless=True, cache_dir="test_cache")+ yield browser+ # Cleanup+ if os.path.exists("test_cache"):+ os.rmdir("test_cache")++[email protected](scope="function")+def browser_toolkit_fixture():+ with patch('playwright.sync_api.sync_playwright'):+ toolkit = BrowserToolkit(headless=True, cache_dir="test_cache")+ yield toolkit+ # Cleanup+ if os.path.exists("test_cache"):+ os.rmdir("test_cache")+++def test_base_browser_init(base_browser_fixture):+ browser = base_browser_fixture+ assert browser.headless is True+ assert browser.cache_dir == "test_cache"+ assert isinstance(browser.history, list)+ assert isinstance(browser.page_history, list)+++def test_base_browser_initialization_order():+ with patch('playwright.sync_api.sync_playwright'):+ browser = BaseBrowser(headless=True) # __init__ called+ assert not hasattr(browser, 'browser') # browser not launched yet+ assert not hasattr(browser, 'page') # page not created yet++ browser.init() # explicit init() call+ assert hasattr(browser, 'browser') # browser launched+ assert hasattr(browser, 'page') # page created+++ "channel",+ [+ ChromiumChannels.CHROME,+ ChromiumChannels.MSEDGE,+ ChromiumChannels.CHROMIUM,+ ],+)+def test_browser_channel_selection(channel: ChromiumChannels):+ with patch('playwright.sync_api.sync_playwright'):+ browser = BaseBrowser(headless=True, channel=channel)+ assert browser.channel == channel.value+++def test_browser_visit_page(base_browser_fixture):+ browser = base_browser_fixture+ browser.init()++ # Mock the page methods+ browser.page.goto = MagicMock()+ browser.page.wait_for_load_state = MagicMock()++ browser.visit_page(TEST_URL)++ browser.page.goto.assert_called_once_with(TEST_URL)+ browser.page.wait_for_load_state.assert_called_once()+++def test_browser_get_screenshot(base_browser_fixture):+ browser = base_browser_fixture+ browser.init()++ # Create a mock image for testing+ mock_image = Image.new('RGB', (100, 100))+ img_byte_arr = io.BytesIO()+ mock_image.save(img_byte_arr, format='PNG')+ img_byte_arr = img_byte_arr.getvalue()++ browser.page.screenshot = MagicMock(return_value=img_byte_arr)++ image, file_path = browser.get_screenshot(save_image=False)+ assert isinstance(image, Image.Image)+ assert file_path is None+++def test_browser_toolkit_browse_url(browser_toolkit_fixture):+ toolkit = browser_toolkit_fixture++ # Mock necessary components+ toolkit.browser.visit_page = MagicMock()+ toolkit._observe = MagicMock(return_value=("obs", "reason", "stop()"))+ toolkit._get_final_answer = MagicMock(return_value="Task completed")++ result = toolkit.browse_url(+ task_prompt="Test task", start_url=TEST_URL, round_limit=1+ )++ assert result == "Task completed"+ toolkit.browser.visit_page.assert_called_once_with(TEST_URL)+++def test_browser_clean_cache(base_browser_fixture):+ browser = base_browser_fixture++ # Create a test file in cache directory+ os.makedirs(browser.cache_dir, exist_ok=True)+ test_file = os.path.join(browser.cache_dir, "test.txt")+ with open(test_file, "w") as f:+ f.write("test")++ browser.clean_cache()+ assert not os.path.exists(browser.cache_dir)+++def test_browser_click_blank_area(base_browser_fixture):+ browser = base_browser_fixture+ browser.init()++ browser.page.mouse.click = MagicMock()+ browser.page.wait_for_load_state = MagicMock()++ browser.click_blank_area()++ browser.page.mouse.click.assert_called_once_with(0, 0)+ browser.page.wait_for_load_state.assert_called_once()+++def test_browser_get_url(base_browser_fixture):+ browser = base_browser_fixture+ browser.init()++ browser.page.url = TEST_URL++ assert browser.get_url() == TEST_URL+++def test_browser_back_navigation(base_browser_fixture):+ browser = base_browser_fixture+ browser.init()++ browser.page.go_back = MagicMock()+ browser.page.wait_for_load_state = MagicMock()++ browser.back()++ browser.page.go_back.assert_called_once()+ browser.page.wait_for_load_state.assert_called_once()