camel-ai 0.2.56__py3-none-any.whl → 0.2.58__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of camel-ai might be problematic. Click here for more details.

@@ -0,0 +1,1800 @@
1
+ # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+ # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
+ import asyncio
15
+ import datetime
16
+ import io
17
+ import json
18
+ import os
19
+ import random
20
+ import re
21
+ import shutil
22
+ import urllib.parse
23
+ from copy import deepcopy
24
+ from typing import (
25
+ TYPE_CHECKING,
26
+ Any,
27
+ BinaryIO,
28
+ Coroutine,
29
+ Dict,
30
+ List,
31
+ Literal,
32
+ Optional,
33
+ Tuple,
34
+ TypedDict,
35
+ Union,
36
+ cast,
37
+ )
38
+
39
+ from PIL import Image, ImageDraw, ImageFont
40
+
41
+ if TYPE_CHECKING:
42
+ from camel.agents import ChatAgent
43
+ from camel.logger import get_logger
44
+ from camel.messages import BaseMessage
45
+ from camel.models import BaseModelBackend, ModelFactory
46
+ from camel.toolkits.base import BaseToolkit
47
+ from camel.toolkits.function_tool import FunctionTool
48
+ from camel.toolkits.video_analysis_toolkit import VideoAnalysisToolkit
49
+ from camel.types import ModelPlatformType, ModelType
50
+ from camel.utils import (
51
+ dependencies_required,
52
+ retry_on_error,
53
+ sanitize_filename,
54
+ )
55
+
56
+ logger = get_logger(__name__)
57
+
58
+ TOP_NO_LABEL_ZONE = 20
59
+
60
+ AVAILABLE_ACTIONS_PROMPT = """
61
+ 1. `fill_input_id(identifier: Union[str, int], text: str)`: Fill an input
62
+ field (e.g. search box) with the given text and press Enter.
63
+ 2. `click_id(identifier: Union[str, int])`: Click an element with the given ID.
64
+ 3. `hover_id(identifier: Union[str, int])`: Hover over an element with the
65
+ given ID.
66
+ 4. `download_file_id(identifier: Union[str, int])`: Download a file with the
67
+ given ID. It returns the path to the downloaded file. If the file is
68
+ successfully downloaded, you can stop the simulation and report the path to
69
+ the downloaded file for further processing.
70
+ 5. `scroll_to_bottom()`: Scroll to the bottom of the page.
71
+ 6. `scroll_to_top()`: Scroll to the top of the page.
72
+ 7. `scroll_up()`: Scroll up the page. It is suitable when you want to see the
73
+ elements above the current viewport.
74
+ 8. `scroll_down()`: Scroll down the page. It is suitable when you want to see
75
+ the elements below the current viewport. If the webpage does not change, It
76
+ means that the webpage has scrolled to the bottom.
77
+ 9. `back()`: Navigate back to the previous page. This is useful when you want
78
+ to go back to the previous page, as current page is not useful.
79
+ 10. `stop()`: Stop the action process, because the task is completed or failed
80
+ (impossible to find the answer). In this situation, you should provide your
81
+ answer in your output.
82
+ 11. `get_url()`: Get the current URL of the current page.
83
+ 12. `find_text_on_page(search_text: str)`: Find the next given text on the
84
+ current whole page, and scroll the page to the targeted text. It is equivalent
85
+ to pressing Ctrl + F and searching for the text, and is powerful when you want
86
+ to fast-check whether the current page contains some specific text.
87
+ 13. `visit_page(url: str)`: Go to the specific url page.
88
+ 14. `click_blank_area()`: Click a blank area of the page to unfocus the
89
+ current element. It is useful when you have clicked an element but it cannot
90
+ unfocus itself (e.g. Menu bar) to automatically render the updated webpage.
91
+ 15. `ask_question_about_video(question: str)`: Ask a question about the
92
+ current webpage which contains video, e.g. youtube websites.
93
+ """
94
+
95
+ ASYNC_ACTIONS = [
96
+ "fill_input_id",
97
+ "click_id",
98
+ "hover_id",
99
+ "download_file_id",
100
+ "scroll_up",
101
+ "scroll_down",
102
+ "scroll_to_bottom",
103
+ "scroll_to_top",
104
+ "back",
105
+ "stop",
106
+ "find_text_on_page",
107
+ "visit_page",
108
+ "click_blank_area",
109
+ ]
110
+
111
+ ACTION_WITH_FEEDBACK_LIST = [
112
+ 'ask_question_about_video',
113
+ 'download_file_id',
114
+ 'find_text_on_page',
115
+ ]
116
+
117
+
118
+ # Code from magentic-one
119
+ class DOMRectangle(TypedDict):
120
+ x: Union[int, float]
121
+ y: Union[int, float]
122
+ width: Union[int, float]
123
+ height: Union[int, float]
124
+ top: Union[int, float]
125
+ right: Union[int, float]
126
+ bottom: Union[int, float]
127
+ left: Union[int, float]
128
+
129
+
130
+ class VisualViewport(TypedDict):
131
+ height: Union[int, float]
132
+ width: Union[int, float]
133
+ offsetLeft: Union[int, float]
134
+ offsetTop: Union[int, float]
135
+ pageLeft: Union[int, float]
136
+ pageTop: Union[int, float]
137
+ scale: Union[int, float]
138
+ clientWidth: Union[int, float]
139
+ clientHeight: Union[int, float]
140
+ scrollWidth: Union[int, float]
141
+ scrollHeight: Union[int, float]
142
+
143
+
144
+ class InteractiveRegion(TypedDict):
145
+ tag_name: str
146
+ role: str
147
+ aria_name: str
148
+ v_scrollable: bool
149
+ rects: List[DOMRectangle]
150
+
151
+
152
+ def extract_function_name(s: str) -> str:
153
+ r"""Extract the pure function name from a string (without parameters or
154
+ parentheses)
155
+
156
+ Args:
157
+ s (str): Input string, e.g., `1.`**`click_id(14)`**, `scroll_up()`,
158
+ `'visit_page(url)'`, etc.
159
+
160
+ Returns:
161
+ str: Pure function name (e.g., `click_id`, `scroll_up`, `visit_page`)
162
+ """
163
+ # 1. Strip leading/trailing whitespace and enclosing backticks or quotes
164
+ s = s.strip().strip('`"\'')
165
+
166
+ # Strip any leading numeric prefix like " 12. " or "3. "
167
+ s = re.sub(r'^\s*\d+\.\s*', '', s)
168
+
169
+ # 3. Match a Python-valid identifier followed by an opening parenthesis
170
+ match = re.match(r'^([A-Za-z_]\w*)\s*\(', s)
171
+ if match:
172
+ return match.group(1)
173
+
174
+ # 4. Fallback: take everything before the first space or '('
175
+ return re.split(r'[ (\n]', s, maxsplit=1)[0]
176
+
177
+
178
+ def _get_str(d: Any, k: str) -> str:
179
+ r"""Safely retrieve a string value from a dictionary."""
180
+ if k not in d:
181
+ raise KeyError(f"Missing required key: '{k}'")
182
+ val = d[k]
183
+ if isinstance(val, str):
184
+ return val
185
+ raise TypeError(
186
+ f"Expected a string for key '{k}', " f"but got {type(val).__name__}"
187
+ )
188
+
189
+
190
+ def _get_number(d: Any, k: str) -> Union[int, float]:
191
+ r"""Safely retrieve a number (int or float) from a dictionary"""
192
+ val = d[k]
193
+ if isinstance(val, (int, float)):
194
+ return val
195
+ raise TypeError(
196
+ f"Expected a number (int/float) for key "
197
+ f"'{k}', but got {type(val).__name__}"
198
+ )
199
+
200
+
201
+ def _get_bool(d: Any, k: str) -> bool:
202
+ r"""Safely retrieve a boolean value from a dictionary."""
203
+ val = d[k]
204
+ if isinstance(val, bool):
205
+ return val
206
+ raise TypeError(
207
+ f"Expected a boolean for key '{k}', " f"but got {type(val).__name__}"
208
+ )
209
+
210
+
211
+ def _parse_json_output(text: str) -> Dict[str, Any]:
212
+ r"""Extract JSON output from a string."""
213
+
214
+ markdown_pattern = r'```(?:json)?\s*(.*?)\s*```'
215
+ markdown_match = re.search(markdown_pattern, text, re.DOTALL)
216
+ if markdown_match:
217
+ text = markdown_match.group(1).strip()
218
+
219
+ triple_quotes_pattern = r'"""(?:json)?\s*(.*?)\s*"""'
220
+ triple_quotes_match = re.search(triple_quotes_pattern, text, re.DOTALL)
221
+ if triple_quotes_match:
222
+ text = triple_quotes_match.group(1).strip()
223
+
224
+ try:
225
+ return json.loads(text)
226
+ except json.JSONDecodeError:
227
+ try:
228
+ fixed_text = re.sub(
229
+ r'`([^`]*?)`(?=\s*[:,\[\]{}]|$)', r'"\1"', text
230
+ )
231
+ return json.loads(fixed_text)
232
+ except json.JSONDecodeError:
233
+ result = {}
234
+ try:
235
+ bool_pattern = r'"(\w+)"\s*:\s*(true|false)'
236
+ for match in re.finditer(bool_pattern, text, re.IGNORECASE):
237
+ key, value = match.groups()
238
+ result[key] = value.lower() == "true"
239
+
240
+ str_pattern = r'"(\w+)"\s*:\s*"([^"]*)"'
241
+ for match in re.finditer(str_pattern, text):
242
+ key, value = match.groups()
243
+ result[key] = value
244
+
245
+ num_pattern = r'"(\w+)"\s*:\s*(-?\d+(?:\.\d+)?)'
246
+ for match in re.finditer(num_pattern, text):
247
+ key, value = match.groups()
248
+ try:
249
+ result[key] = int(value)
250
+ except ValueError:
251
+ result[key] = float(value)
252
+
253
+ empty_str_pattern = r'"(\w+)"\s*:\s*""'
254
+ for match in re.finditer(empty_str_pattern, text):
255
+ key = match.group(1)
256
+ result[key] = ""
257
+
258
+ if result:
259
+ return result
260
+
261
+ logger.warning(f"Failed to parse JSON output: {text}")
262
+ return {}
263
+ except Exception as e:
264
+ logger.warning(f"Error while extracting fields from JSON: {e}")
265
+ return {}
266
+
267
+
268
+ def _reload_image(image: Image.Image):
269
+ buffer = io.BytesIO()
270
+ image.save(buffer, format="PNG")
271
+ buffer.seek(0)
272
+ return Image.open(buffer)
273
+
274
+
275
+ def dom_rectangle_from_dict(rect: Dict[str, Any]) -> DOMRectangle:
276
+ r"""Create a DOMRectangle object from a dictionary."""
277
+ return DOMRectangle(
278
+ x=_get_number(rect, "x"),
279
+ y=_get_number(rect, "y"),
280
+ width=_get_number(rect, "width"),
281
+ height=_get_number(rect, "height"),
282
+ top=_get_number(rect, "top"),
283
+ right=_get_number(rect, "right"),
284
+ bottom=_get_number(rect, "bottom"),
285
+ left=_get_number(rect, "left"),
286
+ )
287
+
288
+
289
+ def interactive_region_from_dict(region: Dict[str, Any]) -> InteractiveRegion:
290
+ r"""Create an :class:`InteractiveRegion` object from a dictionary."""
291
+ typed_rects: List[DOMRectangle] = []
292
+ for rect in region["rects"]:
293
+ typed_rects.append(dom_rectangle_from_dict(rect))
294
+
295
+ return InteractiveRegion(
296
+ tag_name=_get_str(region, "tag_name"),
297
+ role=_get_str(region, "role"),
298
+ aria_name=_get_str(region, "aria-name"),
299
+ v_scrollable=_get_bool(region, "v-scrollable"),
300
+ rects=typed_rects,
301
+ )
302
+
303
+
304
+ def visual_viewport_from_dict(viewport: Dict[str, Any]) -> VisualViewport:
305
+ r"""Create a :class:`VisualViewport` object from a dictionary."""
306
+ return VisualViewport(
307
+ height=_get_number(viewport, "height"),
308
+ width=_get_number(viewport, "width"),
309
+ offsetLeft=_get_number(viewport, "offsetLeft"),
310
+ offsetTop=_get_number(viewport, "offsetTop"),
311
+ pageLeft=_get_number(viewport, "pageLeft"),
312
+ pageTop=_get_number(viewport, "pageTop"),
313
+ scale=_get_number(viewport, "scale"),
314
+ clientWidth=_get_number(viewport, "clientWidth"),
315
+ clientHeight=_get_number(viewport, "clientHeight"),
316
+ scrollWidth=_get_number(viewport, "scrollWidth"),
317
+ scrollHeight=_get_number(viewport, "scrollHeight"),
318
+ )
319
+
320
+
321
+ def add_set_of_mark(
322
+ screenshot: Union[bytes, Image.Image, io.BufferedIOBase],
323
+ ROIs: Dict[str, InteractiveRegion],
324
+ ) -> Tuple[Image.Image, List[str], List[str], List[str]]:
325
+ if isinstance(screenshot, Image.Image):
326
+ return _add_set_of_mark(screenshot, ROIs)
327
+
328
+ if isinstance(screenshot, bytes):
329
+ screenshot = io.BytesIO(screenshot)
330
+
331
+ image = Image.open(cast(BinaryIO, screenshot))
332
+ comp, visible_rects, rects_above, rects_below = _add_set_of_mark(
333
+ image, ROIs
334
+ )
335
+ image.close()
336
+ return comp, visible_rects, rects_above, rects_below
337
+
338
+
339
+ def _add_set_of_mark(
340
+ screenshot: Image.Image, ROIs: Dict[str, InteractiveRegion]
341
+ ) -> Tuple[Image.Image, List[str], List[str], List[str]]:
342
+ r"""Add a set of marks to the screenshot.
343
+
344
+ Args:
345
+ screenshot (Image.Image): The screenshot to add marks to.
346
+ ROIs (Dict[str, InteractiveRegion]): The regions to add marks to.
347
+
348
+ Returns:
349
+ Tuple[Image.Image, List[str], List[str], List[str]]: A tuple
350
+ containing the screenshot with marked ROIs, ROIs fully within the
351
+ images, ROIs located above the visible area, and ROIs located below
352
+ the visible area.
353
+ """
354
+ visible_rects: List[str] = list()
355
+ rects_above: List[str] = list() # Scroll up to see
356
+ rects_below: List[str] = list() # Scroll down to see
357
+
358
+ fnt = ImageFont.load_default(14)
359
+ base = screenshot.convert("L").convert("RGBA")
360
+ overlay = Image.new("RGBA", base.size)
361
+
362
+ draw = ImageDraw.Draw(overlay)
363
+ for r in ROIs:
364
+ for rect in ROIs[r]["rects"]:
365
+ # Empty rectangles
366
+ if not rect or rect["width"] == 0 or rect["height"] == 0:
367
+ continue
368
+
369
+ # TODO: add scroll left and right?
370
+ horizontal_center = (rect["right"] + rect["left"]) / 2.0
371
+ vertical_center = (rect["top"] + rect["bottom"]) / 2.0
372
+ is_within_horizon = 0 <= horizontal_center < base.size[0]
373
+ is_above_viewport = vertical_center < 0
374
+ is_below_viewport = vertical_center >= base.size[1]
375
+
376
+ if is_within_horizon:
377
+ if is_above_viewport:
378
+ rects_above.append(r)
379
+ elif is_below_viewport:
380
+ rects_below.append(r)
381
+ else: # Fully visible
382
+ visible_rects.append(r)
383
+ _draw_roi(draw, int(r), fnt, rect)
384
+
385
+ comp = Image.alpha_composite(base, overlay)
386
+ overlay.close()
387
+ return comp, visible_rects, rects_above, rects_below
388
+
389
+
390
+ def _draw_roi(
391
+ draw: ImageDraw.ImageDraw,
392
+ idx: int,
393
+ font: ImageFont.FreeTypeFont | ImageFont.ImageFont,
394
+ rect: DOMRectangle,
395
+ ) -> None:
396
+ r"""Draw a ROI on the image.
397
+
398
+ Args:
399
+ draw (ImageDraw.ImageDraw): The draw object.
400
+ idx (int): The index of the ROI.
401
+ font (ImageFont.FreeTypeFont | ImageFont.ImageFont): The font.
402
+ rect (DOMRectangle): The DOM rectangle.
403
+ """
404
+ color = _get_random_color(idx)
405
+ text_color = _get_text_color(color)
406
+
407
+ roi = ((rect["left"], rect["top"]), (rect["right"], rect["bottom"]))
408
+
409
+ label_location = (rect["right"], rect["top"])
410
+ label_anchor = "rb"
411
+
412
+ if label_location[1] <= TOP_NO_LABEL_ZONE:
413
+ label_location = (rect["right"], rect["bottom"])
414
+ label_anchor = "rt"
415
+
416
+ draw.rectangle(
417
+ roi, outline=color, fill=(color[0], color[1], color[2], 48), width=2
418
+ )
419
+
420
+ bbox = draw.textbbox(
421
+ label_location,
422
+ str(idx),
423
+ font=font,
424
+ anchor=label_anchor,
425
+ align="center",
426
+ )
427
+ bbox = (bbox[0] - 3, bbox[1] - 3, bbox[2] + 3, bbox[3] + 3)
428
+ draw.rectangle(bbox, fill=color)
429
+
430
+ draw.text(
431
+ label_location,
432
+ str(idx),
433
+ fill=text_color,
434
+ font=font,
435
+ anchor=label_anchor,
436
+ align="center",
437
+ )
438
+
439
+
440
+ def _get_text_color(
441
+ bg_color: Tuple[int, int, int, int],
442
+ ) -> Tuple[int, int, int, int]:
443
+ r"""Determine the ideal text color (black or white) for contrast.
444
+
445
+ Args:
446
+ bg_color: The background color (R, G, B, A).
447
+
448
+ Returns:
449
+ A tuple representing black or white color for text.
450
+ """
451
+ luminance = bg_color[0] * 0.3 + bg_color[1] * 0.59 + bg_color[2] * 0.11
452
+ return (0, 0, 0, 255) if luminance > 120 else (255, 255, 255, 255)
453
+
454
+
455
+ def _get_random_color(identifier: int) -> Tuple[int, int, int, int]:
456
+ r"""Generate a consistent random RGBA color based on the identifier.
457
+
458
+ Args:
459
+ identifier: The ID used as a seed to ensure color consistency.
460
+
461
+ Returns:
462
+ A tuple representing (R, G, B, A) values.
463
+ """
464
+ rnd = random.Random(int(identifier))
465
+ r = rnd.randint(0, 255)
466
+ g = rnd.randint(125, 255)
467
+ b = rnd.randint(0, 50)
468
+ color = [r, g, b]
469
+ # TODO: check why shuffle is needed?
470
+ rnd.shuffle(color)
471
+ color.append(255)
472
+ return cast(Tuple[int, int, int, int], tuple(color))
473
+
474
+
475
+ class AsyncBaseBrowser:
476
+ def __init__(
477
+ self,
478
+ headless=True,
479
+ cache_dir: Optional[str] = None,
480
+ channel: Literal["chrome", "msedge", "chromium"] = "chromium",
481
+ cookie_json_path: Optional[str] = None,
482
+ ):
483
+ r"""
484
+ Initialize the asynchronous browser core.
485
+
486
+ Args:
487
+ headless (bool): Whether to run the browser in headless mode.
488
+ cache_dir (Union[str, None]): The directory to store cache files.
489
+ channel (Literal["chrome", "msedge", "chromium"]): The browser
490
+ channel to use. Must be one of "chrome", "msedge", or
491
+ "chromium".
492
+ cookie_json_path (Optional[str]): Path to a JSON file containing
493
+ authentication cookies and browser storage state. If provided
494
+ and the file exists, the browser will load this state to
495
+ maintain authenticated sessions without requiring manual login.
496
+
497
+ Returns:
498
+ None
499
+ """
500
+ from playwright.async_api import (
501
+ async_playwright,
502
+ )
503
+
504
+ self.history: list = []
505
+ self.headless = headless
506
+ self.channel = channel
507
+ self.playwright = async_playwright()
508
+ self.page_history: list = []
509
+ self.cookie_json_path = cookie_json_path
510
+
511
+ # Set the cache directory
512
+ self.cache_dir = "tmp/" if cache_dir is None else cache_dir
513
+ os.makedirs(self.cache_dir, exist_ok=True)
514
+
515
+ # Load the page script
516
+ abs_dir_path = os.path.dirname(os.path.abspath(__file__))
517
+ page_script_path = os.path.join(abs_dir_path, "page_script.js")
518
+
519
+ try:
520
+ with open(page_script_path, "r", encoding='utf-8') as f:
521
+ self.page_script = f.read()
522
+ f.close()
523
+ except FileNotFoundError:
524
+ raise FileNotFoundError(
525
+ f"Page script file not found at path: {page_script_path}"
526
+ )
527
+
528
+ async def async_init(self) -> None:
529
+ r"""Asynchronously initialize the browser."""
530
+ # Start Playwright asynchronously (only needed in async mode).
531
+ if not getattr(self, "playwright_started", False):
532
+ await self._ensure_browser_installed()
533
+ self.playwright_server = await self.playwright.start()
534
+ self.playwright_started = True
535
+ # Launch the browser asynchronously.
536
+ self.browser = await self.playwright_server.chromium.launch(
537
+ headless=self.headless, channel=self.channel
538
+ )
539
+ # Check if cookie file exists before using it to maintain
540
+ # authenticated sessions. This prevents errors when the cookie file
541
+ # doesn't exist
542
+ if self.cookie_json_path and os.path.exists(self.cookie_json_path):
543
+ self.context = await self.browser.new_context(
544
+ accept_downloads=True, storage_state=self.cookie_json_path
545
+ )
546
+ else:
547
+ self.context = await self.browser.new_context(
548
+ accept_downloads=True,
549
+ )
550
+ # Create a new page asynchronously.
551
+ self.page = await self.context.new_page()
552
+
553
+ def init(self) -> Coroutine[Any, Any, None]:
554
+ r"""Initialize the browser asynchronously."""
555
+ return self.async_init()
556
+
557
+ def clean_cache(self) -> None:
558
+ r"""Delete the cache directory and its contents."""
559
+ if os.path.exists(self.cache_dir):
560
+ shutil.rmtree(self.cache_dir)
561
+
562
+ async def async_wait_for_load(self, timeout: int = 20) -> None:
563
+ r"""
564
+ Asynchronously Wait for a certain amount of time for the page to load.
565
+
566
+ Args:
567
+ timeout (int): Timeout in seconds.
568
+ """
569
+ timeout_ms = timeout * 1000
570
+ await self.page.wait_for_load_state("load", timeout=timeout_ms)
571
+
572
+ # TODO: check if this is needed
573
+ await asyncio.sleep(2)
574
+
575
+ def wait_for_load(self, timeout: int = 20) -> Coroutine[Any, Any, None]:
576
+ r"""Wait for a certain amount of time for the page to load.
577
+
578
+ Args:
579
+ timeout (int): Timeout in seconds.
580
+ """
581
+ return self.async_wait_for_load(timeout)
582
+
583
+ async def async_click_blank_area(self) -> None:
584
+ r"""Asynchronously click a blank area of the page to unfocus
585
+ the current element."""
586
+ await self.page.mouse.click(0, 0)
587
+ await self.wait_for_load()
588
+
589
+ def click_blank_area(self) -> Coroutine[Any, Any, None]:
590
+ r"""Click a blank area of the page to unfocus the current element."""
591
+ return self.async_click_blank_area()
592
+
593
+ async def async_visit_page(self, url: str) -> None:
594
+ r"""Visit a page with the given URL."""
595
+
596
+ await self.page.goto(url)
597
+ await self.wait_for_load()
598
+ self.page_url = url
599
+
600
+ @retry_on_error()
601
+ def visit_page(self, url: str) -> Coroutine[Any, Any, None]:
602
+ r"""Visit a page with the given URL."""
603
+
604
+ return self.async_visit_page(url)
605
+
606
+ def ask_question_about_video(self, question: str) -> str:
607
+ r"""Ask a question about the video on the current page,
608
+ such as YouTube video.
609
+
610
+ Args:
611
+ question (str): The question to ask.
612
+
613
+ Returns:
614
+ str: The answer to the question.
615
+ """
616
+ current_url = self.get_url()
617
+
618
+ # Confirm with user before proceeding due to potential slow
619
+ # processing time
620
+ confirmation_message = (
621
+ f"Do you want to analyze the video on the current "
622
+ f"page({current_url})? This operation may take a long time.(y/n): "
623
+ )
624
+ user_confirmation = input(confirmation_message)
625
+
626
+ if user_confirmation.lower() not in ['y', 'yes']:
627
+ return "User cancelled the video analysis."
628
+
629
+ model = None
630
+ if hasattr(self, 'web_agent_model'):
631
+ model = self.web_agent_model
632
+
633
+ video_analyzer = VideoAnalysisToolkit(model=model)
634
+ result = video_analyzer.ask_question_about_video(current_url, question)
635
+ return result
636
+
637
+ @retry_on_error()
638
+ async def async_get_screenshot(
639
+ self, save_image: bool = False
640
+ ) -> Tuple[Image.Image, Union[str, None]]:
641
+ r"""Asynchronously get a screenshot of the current page.
642
+
643
+ Args:
644
+ save_image (bool): Whether to save the image to the cache
645
+ directory.
646
+
647
+ Returns:
648
+ Tuple[Image.Image, str]: A tuple containing the screenshot
649
+ image and the path to the image file if saved, otherwise
650
+ :obj:`None`.
651
+ """
652
+ image_data = await self.page.screenshot(timeout=60000)
653
+ image = Image.open(io.BytesIO(image_data))
654
+
655
+ file_path = None
656
+ if save_image:
657
+ # Get url name to form a file name
658
+ # Use urlparser for a safer extraction the url name
659
+ parsed_url = urllib.parse.urlparse(self.page_url)
660
+ # Max length is set to 241 as there are 10 characters for the
661
+ # timestamp and 4 characters for the file extension:
662
+ url_name = sanitize_filename(str(parsed_url.path), max_length=241)
663
+ timestamp = datetime.datetime.now().strftime("%m%d%H%M%S")
664
+ file_path = os.path.join(
665
+ self.cache_dir, f"{url_name}_{timestamp}.png"
666
+ )
667
+ with open(file_path, "wb") as f:
668
+ image.save(f, "PNG")
669
+ f.close()
670
+
671
+ return image, file_path
672
+
673
+ @retry_on_error()
674
+ def get_screenshot(
675
+ self, save_image: bool = False
676
+ ) -> Coroutine[Any, Any, Tuple[Image.Image, Union[str, None]]]:
677
+ r"""Get a screenshot of the current page.
678
+
679
+ Args:
680
+ save_image (bool): Whether to save the image to the cache
681
+ directory.
682
+
683
+ Returns:
684
+ Tuple[Image.Image, str]: A tuple containing the screenshot
685
+ image and the path to the image file if saved, otherwise
686
+ :obj:`None`.
687
+ """
688
+ return self.async_get_screenshot(save_image)
689
+
690
+ async def async_capture_full_page_screenshots(
691
+ self, scroll_ratio: float = 0.8
692
+ ) -> List[str]:
693
+ r"""Asynchronously capture full page screenshots by scrolling the
694
+ page with a buffer zone.
695
+
696
+ Args:
697
+ scroll_ratio (float): The ratio of viewport height to scroll each
698
+ step (default: 0.8).
699
+
700
+ Returns:
701
+ List[str]: A list of paths to the captured screenshots.
702
+ """
703
+ screenshots = []
704
+ scroll_height = await self.page.evaluate("document.body.scrollHeight")
705
+ assert self.page.viewport_size is not None
706
+ viewport_height = self.page.viewport_size["height"]
707
+ current_scroll = 0
708
+ screenshot_index = 1
709
+
710
+ max_height = scroll_height - viewport_height
711
+ scroll_step = int(viewport_height * scroll_ratio)
712
+
713
+ last_height = 0
714
+
715
+ while True:
716
+ logger.debug(
717
+ f"Current scroll: {current_scroll}, max_height: "
718
+ f"{max_height}, step: {scroll_step}"
719
+ )
720
+
721
+ _, file_path = await self.get_screenshot(save_image=True)
722
+ screenshots.append(file_path)
723
+
724
+ await self.page.evaluate(f"window.scrollBy(0, {scroll_step})")
725
+ # Allow time for content to load
726
+ await asyncio.sleep(0.5)
727
+
728
+ current_scroll = await self.page.evaluate("window.scrollY")
729
+ # Break if there is no significant scroll
730
+ if abs(current_scroll - last_height) < viewport_height * 0.1:
731
+ break
732
+
733
+ last_height = current_scroll
734
+ screenshot_index += 1
735
+
736
+ return screenshots
737
+
738
+ def capture_full_page_screenshots(
739
+ self, scroll_ratio: float = 0.8
740
+ ) -> Coroutine[Any, Any, List[str]]:
741
+ r"""Capture full page screenshots by scrolling the page with
742
+ a buffer zone.
743
+
744
+ Args:
745
+ scroll_ratio (float): The ratio of viewport height to scroll each
746
+ step (default: 0.8).
747
+
748
+ Returns:
749
+ List[str]: A list of paths to the captured screenshots.
750
+ """
751
+ return self.async_capture_full_page_screenshots(scroll_ratio)
752
+
753
+ async def async_get_visual_viewport(self) -> VisualViewport:
754
+ r"""Asynchronously get the visual viewport of the current page.
755
+
756
+ Returns:
757
+ VisualViewport: The visual viewport of the current page.
758
+ """
759
+ try:
760
+ await self.page.evaluate(self.page_script)
761
+ except Exception as e:
762
+ logger.warning(f"Error evaluating page script: {e}")
763
+
764
+ return visual_viewport_from_dict(
765
+ await self.page.evaluate(
766
+ "MultimodalWebSurfer.getVisualViewport();"
767
+ )
768
+ )
769
+
770
+ def get_visual_viewport(self) -> Coroutine[Any, Any, VisualViewport]:
771
+ r"""Get the visual viewport of the current page."""
772
+ return self.async_get_visual_viewport()
773
+
774
+ async def async_get_interactive_elements(
775
+ self,
776
+ ) -> Dict[str, InteractiveRegion]:
777
+ r"""Asynchronously get the interactive elements of the current page.
778
+
779
+ Returns:
780
+ Dict[str, InteractiveRegion]: A dictionary containing the
781
+ interactive elements of the current page.
782
+ """
783
+ try:
784
+ await self.page.evaluate(self.page_script)
785
+ except Exception as e:
786
+ logger.warning(f"Error evaluating page script: {e}")
787
+
788
+ result = cast(
789
+ Dict[str, Dict[str, Any]],
790
+ await self.page.evaluate(
791
+ "MultimodalWebSurfer.getInteractiveRects();"
792
+ ),
793
+ )
794
+
795
+ typed_results: Dict[str, InteractiveRegion] = {}
796
+ for k in result:
797
+ typed_results[k] = interactive_region_from_dict(result[k])
798
+
799
+ return typed_results # type: ignore[return-value]
800
+
801
+ def get_interactive_elements(
802
+ self,
803
+ ) -> Coroutine[Any, Any, Dict[str, InteractiveRegion]]:
804
+ r"""Get the interactive elements of the current page.
805
+
806
+ Returns:
807
+ Dict[str, InteractiveRegion]: A dictionary of interactive elements.
808
+ """
809
+ return self.async_get_interactive_elements()
810
+
811
+ async def async_get_som_screenshot(
812
+ self,
813
+ save_image: bool = False,
814
+ ) -> Tuple[Image.Image, Union[str, None]]:
815
+ r"""Asynchronously get a screenshot of the current viewport
816
+ with interactive elements marked.
817
+
818
+ Args:
819
+ save_image (bool): Whether to save the image to the cache
820
+ directory.
821
+
822
+ Returns:
823
+ Tuple[Image.Image, str]: A tuple containing the screenshot
824
+ image and the path to the image file.
825
+
826
+ """
827
+
828
+ await self.wait_for_load()
829
+ screenshot, _ = await self.get_screenshot(save_image=False)
830
+ rects = await self.get_interactive_elements()
831
+
832
+ file_path: str | None = None
833
+ comp, _, _, _ = add_set_of_mark(
834
+ screenshot,
835
+ rects, # type: ignore[arg-type]
836
+ )
837
+ if save_image:
838
+ parsed_url = urllib.parse.urlparse(self.page_url)
839
+ # Max length is set to 241 as there are 10 characters for the
840
+ # timestamp and 4 characters for the file extension:
841
+ url_name = sanitize_filename(str(parsed_url.path), max_length=241)
842
+ timestamp = datetime.datetime.now().strftime("%m%d%H%M%S")
843
+ file_path = os.path.join(
844
+ self.cache_dir, f"{url_name}_{timestamp}.png"
845
+ )
846
+ with open(file_path, "wb") as f:
847
+ comp.save(f, "PNG")
848
+ f.close()
849
+
850
+ return comp, file_path
851
+
852
+ def get_som_screenshot(
853
+ self,
854
+ save_image: bool = False,
855
+ ) -> Coroutine[Any, Any, Tuple[Image.Image, Union[str, None]]]:
856
+ r"""Get a screenshot of the current viewport with interactive elements
857
+ marked.
858
+
859
+ Args:
860
+ save_image (bool): Whether to save the image to the cache
861
+ directory.
862
+
863
+ Returns:
864
+ Tuple[Image.Image, str]: A tuple containing the screenshot image
865
+ and the path to the image file.
866
+ """
867
+ return self.async_get_som_screenshot(save_image)
868
+
869
+ async def async_scroll_up(self) -> None:
870
+ r"""Asynchronously scroll up the page."""
871
+ await self.page.keyboard.press("PageUp")
872
+
873
+ def scroll_up(self) -> Coroutine[Any, Any, None]:
874
+ r"""Scroll up the page."""
875
+ return self.async_scroll_up()
876
+
877
+ async def async_scroll_down(self) -> None:
878
+ r"""Asynchronously scroll down the page."""
879
+ await self.page.keyboard.press("PageDown")
880
+
881
+ def scroll_down(self) -> Coroutine[Any, Any, None]:
882
+ r"""Scroll down the page."""
883
+ return self.async_scroll_down()
884
+
885
+ def get_url(self) -> str:
886
+ r"""Get the URL of the current page."""
887
+ return self.page.url
888
+
889
+ async def async_click_id(self, identifier: Union[str, int]) -> None:
890
+ r"""Asynchronously click an element with the given ID.
891
+
892
+ Args:
893
+ identifier (Union[str, int]): The ID of the element to click.
894
+ """
895
+ if isinstance(identifier, int):
896
+ identifier = str(identifier)
897
+ target = self.page.locator(f"[__elementId='{identifier}']")
898
+
899
+ try:
900
+ await target.wait_for(timeout=5000)
901
+ except (TimeoutError, Exception) as e:
902
+ logger.debug(f"Error during click operation: {e}")
903
+ raise ValueError("No such element.") from None
904
+
905
+ await target.scroll_into_view_if_needed()
906
+
907
+ new_page = None
908
+ try:
909
+ async with self.page.expect_event(
910
+ "popup", timeout=1000
911
+ ) as page_info:
912
+ box = cast(
913
+ Dict[str, Union[int, float]], await target.bounding_box()
914
+ )
915
+ await self.page.mouse.click(
916
+ box["x"] + box["width"] / 2, box["y"] + box["height"] / 2
917
+ )
918
+ new_page = await page_info.value
919
+
920
+ # If a new page is opened, switch to it
921
+ if new_page:
922
+ self.page_history.append(deepcopy(self.page.url))
923
+ self.page = new_page
924
+
925
+ except (TimeoutError, Exception) as e:
926
+ logger.debug(f"Error during click operation: {e}")
927
+ pass
928
+
929
+ await self.wait_for_load()
930
+
931
+ def click_id(
932
+ self, identifier: Union[str, int]
933
+ ) -> Coroutine[Any, Any, None]:
934
+ r"""Click an element with the given identifier."""
935
+ return self.async_click_id(identifier)
936
+
937
+ async def async_extract_url_content(self) -> str:
938
+ r"""Asynchronously extract the content of the current page."""
939
+ content = await self.page.content()
940
+ return content
941
+
942
+ def extract_url_content(self) -> Coroutine[Any, Any, str]:
943
+ r"""Extract the content of the current page."""
944
+ return self.async_extract_url_content()
945
+
946
+ async def async_download_file_id(self, identifier: Union[str, int]) -> str:
947
+ r"""Asynchronously download a file with the given selector.
948
+
949
+ Args:
950
+ identifier (Union[str, int]): The identifier of the file
951
+ to download.
952
+
953
+ Returns:
954
+ str: The path to the downloaded file.
955
+ """
956
+
957
+ if isinstance(identifier, int):
958
+ identifier = str(identifier)
959
+ try:
960
+ target = self.page.locator(f"[__elementId='{identifier}']")
961
+ except (TimeoutError, Exception) as e:
962
+ logger.debug(f"Error during download operation: {e}")
963
+ logger.warning(
964
+ f"Element with identifier '{identifier}' not found."
965
+ )
966
+ return f"Element with identifier '{identifier}' not found."
967
+
968
+ await target.scroll_into_view_if_needed()
969
+
970
+ file_path = os.path.join(self.cache_dir)
971
+ await self.wait_for_load()
972
+
973
+ try:
974
+ async with self.page.expect_download(
975
+ timeout=5000
976
+ ) as download_info:
977
+ await target.click()
978
+ download = await download_info.value
979
+ file_name = download.suggested_filename
980
+
981
+ file_path = os.path.join(file_path, file_name)
982
+ await download.save_as(file_path)
983
+
984
+ return f"Downloaded file to path '{file_path}'."
985
+
986
+ except Exception as e:
987
+ logger.debug(f"Error during download operation: {e}")
988
+ return f"Failed to download file with identifier '{identifier}'."
989
+
990
+ def download_file_id(
991
+ self, identifier: Union[str, int]
992
+ ) -> Coroutine[Any, Any, str]:
993
+ r"""Download a file with the given identifier."""
994
+ return self.async_download_file_id(identifier)
995
+
996
+ async def async_fill_input_id(
997
+ self, identifier: Union[str, int], text: str
998
+ ) -> str:
999
+ r"""Asynchronously fill an input field with the given text, and then
1000
+ press Enter.
1001
+
1002
+ Args:
1003
+ identifier (Union[str, int]): The identifier of the input field.
1004
+ text (str): The text to fill.
1005
+
1006
+ Returns:
1007
+ str: The result of the action.
1008
+ """
1009
+ if isinstance(identifier, int):
1010
+ identifier = str(identifier)
1011
+
1012
+ try:
1013
+ target = self.page.locator(f"[__elementId='{identifier}']")
1014
+ except (TimeoutError, Exception) as e:
1015
+ logger.debug(f"Error during fill operation: {e}")
1016
+ logger.warning(
1017
+ f"Element with identifier '{identifier}' not found."
1018
+ )
1019
+ return f"Element with identifier '{identifier}' not found."
1020
+
1021
+ await target.scroll_into_view_if_needed()
1022
+ await target.focus()
1023
+ try:
1024
+ await target.fill(text)
1025
+ except Exception as e:
1026
+ logger.debug(f"Error during fill operation: {e}")
1027
+ await target.press_sequentially(text)
1028
+
1029
+ await target.press("Enter")
1030
+ await self.wait_for_load()
1031
+ return (
1032
+ f"Filled input field '{identifier}' with text '{text}' "
1033
+ f"and pressed Enter."
1034
+ )
1035
+
1036
+ def fill_input_id(
1037
+ self, identifier: Union[str, int], text: str
1038
+ ) -> Coroutine[Any, Any, str]:
1039
+ r"""Fill an input field with the given text, and then press Enter."""
1040
+ return self.async_fill_input_id(identifier, text)
1041
+
1042
+ async def async_scroll_to_bottom(self) -> str:
1043
+ r"""Asynchronously scroll to the bottom of the page."""
1044
+ await self.page.evaluate(
1045
+ "window.scrollTo(0, document.body.scrollHeight);"
1046
+ )
1047
+ await self.wait_for_load()
1048
+ return "Scrolled to the bottom of the page."
1049
+
1050
+ def scroll_to_bottom(self) -> Coroutine[Any, Any, str]:
1051
+ r"""Scroll to the bottom of the page."""
1052
+ return self.async_scroll_to_bottom()
1053
+
1054
+ async def async_scroll_to_top(self) -> str:
1055
+ r"""Asynchronously scroll to the top of the page."""
1056
+ await self.page.evaluate("window.scrollTo(0, 0);")
1057
+ await self.wait_for_load()
1058
+ return "Scrolled to the top of the page."
1059
+
1060
+ def scroll_to_top(self) -> Coroutine[Any, Any, str]:
1061
+ r"""Scroll to the top of the page."""
1062
+ return self.async_scroll_to_top()
1063
+
1064
+ async def async_hover_id(self, identifier: Union[str, int]) -> str:
1065
+ r"""Asynchronously hover over an element with the given identifier.
1066
+
1067
+ Args:
1068
+ identifier (Union[str, int]): The identifier of the element
1069
+ to hover over.
1070
+
1071
+ Returns:
1072
+ str: The result of the action.
1073
+ """
1074
+ if isinstance(identifier, int):
1075
+ identifier = str(identifier)
1076
+ try:
1077
+ target = self.page.locator(f"[__elementId='{identifier}']")
1078
+ except (TimeoutError, Exception) as e:
1079
+ logger.debug(f"Error during hover operation: {e}")
1080
+ logger.warning(
1081
+ f"Element with identifier '{identifier}' not found."
1082
+ )
1083
+ return f"Element with identifier '{identifier}' not found."
1084
+
1085
+ await target.scroll_into_view_if_needed()
1086
+ await target.hover()
1087
+ await self.wait_for_load()
1088
+ return f"Hovered over element with identifier '{identifier}'."
1089
+
1090
+ def hover_id(
1091
+ self, identifier: Union[str, int]
1092
+ ) -> Coroutine[Any, Any, str]:
1093
+ r"""Hover over an element with the given identifier."""
1094
+ return self.async_hover_id(identifier)
1095
+
1096
+ async def async_find_text_on_page(self, search_text: str) -> str:
1097
+ r"""Asynchronously find the next given text on the page.It is
1098
+ equivalent to pressing Ctrl + F and searching for the text.
1099
+
1100
+ Args:
1101
+ search_text (str): The text to search for.
1102
+
1103
+ Returns:
1104
+ str: The result of the action.
1105
+ """
1106
+ script = f"""
1107
+ (function() {{
1108
+ let text = "{search_text}";
1109
+ let found = window.find(text);
1110
+ if (!found) {{
1111
+ let elements = document.querySelectorAll(
1112
+ "*:not(script):not(style)"
1113
+ );
1114
+ for (let el of elements) {{
1115
+ if (el.innerText && el.innerText.includes(text)) {{
1116
+ el.scrollIntoView({{
1117
+ behavior: "smooth",
1118
+ block: "center"
1119
+ }});
1120
+ el.style.backgroundColor = "yellow";
1121
+ el.style.border = '2px solid red';
1122
+ return true;
1123
+ }}
1124
+ }}
1125
+ return false;
1126
+ }}
1127
+ return true;
1128
+ }})();
1129
+ """
1130
+ found = await self.page.evaluate(script)
1131
+ await self.wait_for_load()
1132
+ if found:
1133
+ return f"Found text '{search_text}' on the page."
1134
+ else:
1135
+ return f"Text '{search_text}' not found on the page."
1136
+
1137
+ def find_text_on_page(self, search_text: str) -> Coroutine[Any, Any, str]:
1138
+ r"""Find the next given text on the page, and scroll the page to
1139
+ the targeted text. It is equivalent to pressing Ctrl + F and
1140
+ searching for the text.
1141
+
1142
+ Args:
1143
+ search_text (str): The text to search for.
1144
+
1145
+ Returns:
1146
+ str: The result of the action.
1147
+ """
1148
+ return self.async_find_text_on_page(search_text)
1149
+
1150
+ async def async_back(self) -> None:
1151
+ r"""Asynchronously navigate back to the previous page."""
1152
+
1153
+ page_url_before = self.page.url
1154
+ await self.page.go_back()
1155
+
1156
+ page_url_after = self.page.url
1157
+
1158
+ if page_url_after == "about:blank":
1159
+ await self.visit_page(page_url_before)
1160
+
1161
+ if page_url_before == page_url_after:
1162
+ # If the page is not changed, try to use the history
1163
+ if len(self.page_history) > 0:
1164
+ await self.visit_page(self.page_history.pop())
1165
+
1166
+ await asyncio.sleep(1)
1167
+ await self.wait_for_load()
1168
+
1169
+ def back(self) -> Coroutine[Any, Any, None]:
1170
+ r"""Navigate back to the previous page."""
1171
+ return self.async_back()
1172
+
1173
+ async def async_close(self) -> None:
1174
+ r"""Asynchronously close the browser."""
1175
+ await self.browser.close()
1176
+
1177
+ def close(self) -> Coroutine[Any, Any, None]:
1178
+ r"""Close the browser."""
1179
+ return self.async_close()
1180
+
1181
+ async def async_show_interactive_elements(self) -> None:
1182
+ r"""Asynchronously show simple interactive elements on
1183
+ the current page."""
1184
+ await self.page.evaluate(self.page_script)
1185
+ await self.page.evaluate("""
1186
+ () => {
1187
+ document.querySelectorAll(
1188
+ 'a, button, input, select, textarea, ' +
1189
+ '[tabindex]:not([tabindex="-1"]), ' +
1190
+ '[contenteditable="true"]'
1191
+ ).forEach(el => {
1192
+ el.style.border = '2px solid red';
1193
+ });
1194
+ }
1195
+ """)
1196
+
1197
+ def show_interactive_elements(self) -> Coroutine[Any, Any, None]:
1198
+ r"""Show simple interactive elements on the current page."""
1199
+ return self.async_show_interactive_elements()
1200
+
1201
+ async def async_get_webpage_content(self) -> str:
1202
+ r"""Asynchronously extract the content of the current page and convert
1203
+ it to markdown."""
1204
+ from html2text import html2text
1205
+
1206
+ await self.wait_for_load()
1207
+ html_content = await self.page.content()
1208
+
1209
+ markdown_content = html2text(html_content)
1210
+ return markdown_content
1211
+
1212
+ @retry_on_error()
1213
+ def get_webpage_content(self) -> Coroutine[Any, Any, str]:
1214
+ r"""Extract the content of the current page."""
1215
+ return self.async_get_webpage_content()
1216
+
1217
+ async def async_ensure_browser_installed(self) -> None:
1218
+ r"""Ensure the browser is installed."""
1219
+
1220
+ import platform
1221
+ import sys
1222
+
1223
+ try:
1224
+ from playwright.async_api import async_playwright
1225
+
1226
+ async with async_playwright() as p:
1227
+ browser = await p.chromium.launch(channel=self.channel)
1228
+ await browser.close()
1229
+ except Exception:
1230
+ logger.info("Installing Chromium browser...")
1231
+ try:
1232
+ proc1 = await asyncio.create_subprocess_exec(
1233
+ sys.executable,
1234
+ "-m",
1235
+ "playwright",
1236
+ "install",
1237
+ self.channel,
1238
+ stdout=asyncio.subprocess.PIPE,
1239
+ stderr=asyncio.subprocess.PIPE,
1240
+ )
1241
+ stdout, stderr = await proc1.communicate()
1242
+ if proc1.returncode != 0:
1243
+ raise RuntimeError(
1244
+ f"Failed to install browser: {stderr.decode()}"
1245
+ )
1246
+
1247
+ if platform.system().lower() == "linux":
1248
+ proc2 = await asyncio.create_subprocess_exec(
1249
+ sys.executable,
1250
+ "-m",
1251
+ "playwright",
1252
+ "install-deps",
1253
+ self.channel,
1254
+ stdout=asyncio.subprocess.PIPE,
1255
+ stderr=asyncio.subprocess.PIPE,
1256
+ )
1257
+ stdout2, stderr2 = await proc2.communicate()
1258
+ if proc2.returncode != 0:
1259
+ error_message = stderr2.decode()
1260
+ raise RuntimeError(
1261
+ f"Failed to install dependencies: {error_message}"
1262
+ )
1263
+
1264
+ logger.info("Chromium browser installation completed")
1265
+ except Exception as e:
1266
+ raise RuntimeError(f"Installation failed: {e}")
1267
+
1268
+ def _ensure_browser_installed(self) -> Coroutine[Any, Any, None]:
1269
+ r"""Ensure the browser is installed."""
1270
+ return self.async_ensure_browser_installed()
1271
+
1272
+
1273
+ class AsyncBrowserToolkit(BaseToolkit):
1274
+ r"""An asynchronous class for browsing the web and interacting
1275
+ with web pages.
1276
+
1277
+ This class provides methods for browsing the web and interacting with web
1278
+ pages.
1279
+ """
1280
+
1281
+ def __init__(
1282
+ self,
1283
+ headless: bool = False,
1284
+ cache_dir: Optional[str] = None,
1285
+ channel: Literal["chrome", "msedge", "chromium"] = "chromium",
1286
+ history_window: int = 5,
1287
+ web_agent_model: Optional[BaseModelBackend] = None,
1288
+ planning_agent_model: Optional[BaseModelBackend] = None,
1289
+ output_language: str = "en",
1290
+ cookie_json_path: Optional[str] = None,
1291
+ ):
1292
+ r"""Initialize the BrowserToolkit instance.
1293
+
1294
+ Args:
1295
+ headless (bool): Whether to run the browser in headless mode.
1296
+ cache_dir (Union[str, None]): The directory to store cache files.
1297
+ channel (Literal["chrome", "msedge", "chromium"]): The browser
1298
+ channel to use. Must be one of "chrome", "msedge", or
1299
+ "chromium".
1300
+ history_window (int): The window size for storing the history of
1301
+ actions.
1302
+ web_agent_model (Optional[BaseModelBackend]): The model backend
1303
+ for the web agent.
1304
+ planning_agent_model (Optional[BaseModelBackend]): The model
1305
+ backend for the planning agent.
1306
+ output_language (str): The language to use for output.
1307
+ (default: :obj:`"en`")
1308
+ cookie_json_path (Optional[str]): Path to a JSON file containing
1309
+ authentication cookies and browser storage state. If provided
1310
+ and the file exists, the browser will load this state to
1311
+ maintain authenticated sessions without requiring manual
1312
+ login.
1313
+ (default: :obj:`None`)
1314
+ """
1315
+
1316
+ self.browser = AsyncBaseBrowser(
1317
+ headless=headless,
1318
+ cache_dir=cache_dir,
1319
+ channel=channel,
1320
+ cookie_json_path=cookie_json_path,
1321
+ )
1322
+
1323
+ self.history_window = history_window
1324
+ self.web_agent_model = web_agent_model
1325
+ self.planning_agent_model = planning_agent_model
1326
+ self.output_language = output_language
1327
+
1328
+ self.history: list = []
1329
+ self.web_agent, self.planning_agent = self._initialize_agent()
1330
+
1331
+ def _reset(self):
1332
+ self.web_agent.reset()
1333
+ self.planning_agent.reset()
1334
+ self.history = []
1335
+ os.makedirs(self.browser.cache_dir, exist_ok=True)
1336
+
1337
+ def _initialize_agent(self) -> Tuple["ChatAgent", "ChatAgent"]:
1338
+ r"""Initialize the agent."""
1339
+ from camel.agents import ChatAgent
1340
+
1341
+ if self.web_agent_model is None:
1342
+ web_agent_model = ModelFactory.create(
1343
+ model_platform=ModelPlatformType.OPENAI,
1344
+ model_type=ModelType.GPT_4_1,
1345
+ model_config_dict={"temperature": 0, "top_p": 1},
1346
+ )
1347
+ else:
1348
+ web_agent_model = self.web_agent_model
1349
+
1350
+ if self.planning_agent_model is None:
1351
+ planning_model = ModelFactory.create(
1352
+ model_platform=ModelPlatformType.OPENAI,
1353
+ model_type=ModelType.O3_MINI,
1354
+ )
1355
+ else:
1356
+ planning_model = self.planning_agent_model
1357
+
1358
+ system_prompt = """
1359
+ You are a helpful web agent that can assist users in browsing the web.
1360
+ Given a high-level task, you can leverage predefined browser tools to help
1361
+ users achieve their goals.
1362
+ """
1363
+
1364
+ web_agent = ChatAgent(
1365
+ system_message=system_prompt,
1366
+ model=web_agent_model,
1367
+ output_language=self.output_language,
1368
+ )
1369
+
1370
+ planning_system_prompt = """
1371
+ You are a helpful planning agent that can assist users in planning complex
1372
+ tasks which need multi-step browser interaction.
1373
+ """
1374
+
1375
+ planning_agent = ChatAgent(
1376
+ system_message=planning_system_prompt,
1377
+ model=planning_model,
1378
+ output_language=self.output_language,
1379
+ )
1380
+
1381
+ return web_agent, planning_agent
1382
+
1383
+ async def async_observe(
1384
+ self, task_prompt: str, detailed_plan: Optional[str] = None
1385
+ ) -> Tuple[str, str, str]:
1386
+ r"""Let agent observe the current environment, and get the next
1387
+ action."""
1388
+
1389
+ detailed_plan_prompt = ""
1390
+
1391
+ if detailed_plan is not None:
1392
+ detailed_plan_prompt = f"""
1393
+ Here is a plan about how to solve the task step-by-step which you must follow:
1394
+ <detailed_plan>{detailed_plan}<detailed_plan>
1395
+ """
1396
+
1397
+ observe_prompt = f"""
1398
+ Please act as a web agent to help me complete the following high-level task:
1399
+ <task>{task_prompt}</task>
1400
+ Now, I have made screenshot (only the current viewport, not the full webpage)
1401
+ based on the current browser state, and marked interactive elements in the
1402
+ webpage.
1403
+ Please carefully examine the requirements of the task, and current state of
1404
+ the browser, and provide the next appropriate action to take.
1405
+
1406
+ {detailed_plan_prompt}
1407
+
1408
+ Here are the current available browser functions you can use:
1409
+ {AVAILABLE_ACTIONS_PROMPT}
1410
+
1411
+ Here are the latest {self.history_window} trajectory (at most) you have taken:
1412
+ <history>
1413
+ {self.history[-self.history_window :]}
1414
+ </history>
1415
+
1416
+ Your output should be in json format, including the following fields:
1417
+ - `observation`: The detailed image description about the current viewport. Do
1418
+ not over-confident about the correctness of the history actions. You should
1419
+ always check the current viewport to make sure the correctness of the next
1420
+ action.
1421
+ - `reasoning`: The reasoning about the next action you want to take, and the
1422
+ possible obstacles you may encounter, and how to solve them. Do not forget to
1423
+ check the history actions to avoid the same mistakes.
1424
+ - `action_code`: The action code you want to take. It is only one step action
1425
+ code, without any other texts (such as annotation)
1426
+
1427
+ Here is two example of the output:
1428
+ ```json
1429
+ {{
1430
+ "observation": [IMAGE_DESCRIPTION],
1431
+ "reasoning": [YOUR_REASONING],
1432
+ "action_code": "fill_input_id([ID], [TEXT])"
1433
+ }}
1434
+
1435
+ {{
1436
+ "observation": "The current page is a CAPTCHA verification page on Amazon. It asks the user to ..",
1437
+ "reasoning": "To proceed with the task of searching for products, I need to complete..",
1438
+ "action_code": "fill_input_id(3, 'AUXPMR')"
1439
+ }}
1440
+
1441
+ Here are some tips for you:
1442
+ - Never forget the overall question: **{task_prompt}**
1443
+ - Maybe after a certain operation (e.g. click_id), the page content has not
1444
+ changed. You can check whether the action step is successful by looking at the
1445
+ `success` of the action step in the history. If successful, it means that the
1446
+ page content is indeed the same after the click. You need to try other methods.
1447
+ - If using one way to solve the problem is not successful, try other ways.
1448
+ Make sure your provided ID is correct!
1449
+ - Some cases are very complex and need to be achieve by an iterative process.
1450
+ You can use the `back()` function to go back to the previous page to try other
1451
+ methods.
1452
+ - There are many links on the page, which may be useful for solving the
1453
+ problem. You can use the `click_id()` function to click on the link to see if
1454
+ it is useful.
1455
+ - Always keep in mind that your action must be based on the ID shown in the
1456
+ current image or viewport, not the ID shown in the history.
1457
+ - Do not use `stop()` lightly. Always remind yourself that the image only
1458
+ shows a part of the full page. If you cannot find the answer, try to use
1459
+ functions like `scroll_up()` and `scroll_down()` to check the full content of
1460
+ the webpage before doing anything else, because the answer or next key step
1461
+ may be hidden in the content below.
1462
+ - If the webpage needs human verification, you must avoid processing it.
1463
+ Please use `back()` to go back to the previous page, and try other ways.
1464
+ - If you have tried everything and still cannot resolve the issue, please stop
1465
+ the simulation, and report issues you have encountered.
1466
+ - Check the history actions carefully, detect whether you have repeatedly made
1467
+ the same actions or not.
1468
+ - When dealing with wikipedia revision history related tasks, you need to
1469
+ think about the solution flexibly. First, adjust the browsing history
1470
+ displayed on a single page to the maximum, and then make use of the
1471
+ find_text_on_page function. This is extremely useful which can quickly locate
1472
+ the text you want to find and skip massive amount of useless information.
1473
+ - Flexibly use interactive elements like slide down selection bar to filter
1474
+ out the information you need. Sometimes they are extremely useful.
1475
+ ```
1476
+ """ # noqa: E501
1477
+
1478
+ # get current state
1479
+ som_screenshot, _ = await self.browser.get_som_screenshot(
1480
+ save_image=True
1481
+ )
1482
+ img = _reload_image(som_screenshot)
1483
+ message = BaseMessage.make_user_message(
1484
+ role_name='user', content=observe_prompt, image_list=[img]
1485
+ )
1486
+ # Reset the history message of web_agent.
1487
+ self.web_agent.reset()
1488
+ resp = self.web_agent.step(message)
1489
+
1490
+ resp_content = resp.msgs[0].content
1491
+
1492
+ resp_dict = _parse_json_output(resp_content)
1493
+ observation_result: str = resp_dict.get("observation", "")
1494
+ reasoning_result: str = resp_dict.get("reasoning", "")
1495
+ action_code: str = resp_dict.get("action_code", "")
1496
+
1497
+ if action_code and "(" in action_code and ")" not in action_code:
1498
+ action_match = re.search(
1499
+ r'"action_code"\s*:\s*[`"]([^`"]*\([^)]*\))[`"]', resp_content
1500
+ )
1501
+ if action_match:
1502
+ action_code = action_match.group(1)
1503
+ else:
1504
+ logger.warning(
1505
+ f"Incomplete action_code detected: {action_code}"
1506
+ )
1507
+ if action_code.startswith("fill_input_id("):
1508
+ parts = action_code.split(",", 1)
1509
+ if len(parts) > 1:
1510
+ id_part = (
1511
+ parts[0].replace("fill_input_id(", "").strip()
1512
+ )
1513
+ action_code = (
1514
+ f"fill_input_id({id_part}, "
1515
+ f"'Please fill the text here.')"
1516
+ )
1517
+ action_code = action_code.replace("`", "").strip()
1518
+
1519
+ return observation_result, reasoning_result, action_code
1520
+
1521
+ async def async_act(self, action_code: str) -> Tuple[bool, str]:
1522
+ r"""Let agent act based on the given action code.
1523
+ Args:
1524
+ action_code (str): The action code to act.
1525
+
1526
+ Returns:
1527
+ Tuple[bool, str]: A tuple containing a boolean indicating whether
1528
+ the action was successful, and the information to be returned.
1529
+ """
1530
+
1531
+ def _check_if_with_feedback(action_code: str) -> bool:
1532
+ r"""Check if the action code needs feedback."""
1533
+
1534
+ for action_with_feedback in ACTION_WITH_FEEDBACK_LIST:
1535
+ if action_with_feedback in action_code:
1536
+ return True
1537
+
1538
+ return False
1539
+
1540
+ def _fix_action_code(action_code: str) -> str:
1541
+ r"""Fix potential missing quotes in action code"""
1542
+
1543
+ match = re.match(r'(\w+)\((.*)\)', action_code)
1544
+ if not match:
1545
+ return action_code
1546
+
1547
+ func_name, args_str = match.groups()
1548
+
1549
+ args = []
1550
+ current_arg = ""
1551
+ in_quotes = False
1552
+ quote_char = None
1553
+
1554
+ for char in args_str:
1555
+ if char in ['"', "'"]:
1556
+ if not in_quotes:
1557
+ in_quotes = True
1558
+ quote_char = char
1559
+ current_arg += char
1560
+ elif char == quote_char:
1561
+ in_quotes = False
1562
+ quote_char = None
1563
+ current_arg += char
1564
+ else:
1565
+ current_arg += char
1566
+ elif char == ',' and not in_quotes:
1567
+ args.append(current_arg.strip())
1568
+ current_arg = ""
1569
+ else:
1570
+ current_arg += char
1571
+
1572
+ if current_arg:
1573
+ args.append(current_arg.strip())
1574
+
1575
+ fixed_args = []
1576
+ for arg in args:
1577
+ if (
1578
+ (arg.startswith('"') and arg.endswith('"'))
1579
+ or (arg.startswith("'") and arg.endswith("'"))
1580
+ or re.match(r'^-?\d+(\.\d+)?$', arg)
1581
+ or re.match(r'^-?\d+\.?\d*[eE][-+]?\d+$', arg)
1582
+ or re.match(r'^0[xX][0-9a-fA-F]+$', arg)
1583
+ ):
1584
+ fixed_args.append(arg)
1585
+
1586
+ else:
1587
+ fixed_args.append(f"'{arg}'")
1588
+
1589
+ return f"{func_name}({', '.join(fixed_args)})"
1590
+
1591
+ action_code = _fix_action_code(action_code)
1592
+ prefix = "self.browser."
1593
+ code = f"{prefix}{action_code}"
1594
+ async_flag = extract_function_name(action_code) in ASYNC_ACTIONS
1595
+ feedback_flag = _check_if_with_feedback(action_code)
1596
+
1597
+ try:
1598
+ result = "Action was successful."
1599
+ if async_flag:
1600
+ temp_coroutine = eval(code)
1601
+ if feedback_flag:
1602
+ result = await temp_coroutine
1603
+ else:
1604
+ await temp_coroutine
1605
+ await asyncio.sleep(1)
1606
+ return True, result
1607
+ else:
1608
+ if feedback_flag:
1609
+ result = eval(code)
1610
+ else:
1611
+ exec(code)
1612
+ await asyncio.sleep(1)
1613
+ return True, result
1614
+
1615
+ except Exception as e:
1616
+ await asyncio.sleep(1)
1617
+ return (
1618
+ False,
1619
+ f"Error while executing the action {action_code}: {e}. "
1620
+ f"If timeout, please recheck whether you have provided the "
1621
+ f"correct identifier.",
1622
+ )
1623
+
1624
+ def _get_final_answer(self, task_prompt: str) -> str:
1625
+ r"""Get the final answer based on the task prompt and current browser
1626
+ state. It is used when the agent thinks that the task can be completed
1627
+ without any further action, and answer can be directly found in the
1628
+ current viewport.
1629
+ """
1630
+
1631
+ prompt = f"""
1632
+ We are solving a complex web task which needs multi-step browser interaction. After the multi-step observation, reasoning and acting with web browser, we think that the task is currently solved.
1633
+ Here are all trajectory we have taken:
1634
+ <history>{self.history}</history>
1635
+ Please find the final answer, or give valuable insights and founds (e.g. if previous actions contain downloading files, your output should include the path of the downloaded file) about the overall task: <task>{task_prompt}</task>
1636
+ """ # noqa: E501
1637
+
1638
+ message = BaseMessage.make_user_message(
1639
+ role_name='user',
1640
+ content=prompt,
1641
+ )
1642
+
1643
+ resp = self.web_agent.step(message)
1644
+ return resp.msgs[0].content
1645
+
1646
+ def _task_planning(self, task_prompt: str, start_url: str) -> str:
1647
+ r"""Plan the task based on the given task prompt."""
1648
+
1649
+ # Here are the available browser functions we can
1650
+ # use: {AVAILABLE_ACTIONS_PROMPT}
1651
+
1652
+ planning_prompt = f"""
1653
+ <task>{task_prompt}</task>
1654
+ According to the problem above, if we use browser interaction, what is the general process of the interaction after visiting the webpage `{start_url}`?
1655
+
1656
+ Please note that it can be viewed as Partially Observable MDP. Do not over-confident about your plan.
1657
+ Please first restate the task in detail, and then provide a detailed plan to solve the task.
1658
+ """ # noqa: E501
1659
+
1660
+ message = BaseMessage.make_user_message(
1661
+ role_name='user', content=planning_prompt
1662
+ )
1663
+
1664
+ resp = self.planning_agent.step(message)
1665
+ return resp.msgs[0].content
1666
+
1667
+ def _task_replanning(
1668
+ self, task_prompt: str, detailed_plan: str
1669
+ ) -> Tuple[bool, str]:
1670
+ r"""Replan the task based on the given task prompt.
1671
+
1672
+ Args:
1673
+ task_prompt (str): The original task prompt.
1674
+ detailed_plan (str): The detailed plan to replan.
1675
+
1676
+ Returns:
1677
+ Tuple[bool, str]: A tuple containing a boolean indicating
1678
+ whether the task needs to be replanned, and the replanned
1679
+ schema.
1680
+ """
1681
+
1682
+ # Here are the available browser functions we can
1683
+ # use: {AVAILABLE_ACTIONS_PROMPT}
1684
+ replanning_prompt = f"""
1685
+ We are using browser interaction to solve a complex task which needs multi-step actions.
1686
+ Here are the overall task:
1687
+ <overall_task>{task_prompt}</overall_task>
1688
+
1689
+ In order to solve the task, we made a detailed plan previously. Here is the detailed plan:
1690
+ <detailed plan>{detailed_plan}</detailed plan>
1691
+
1692
+ According to the task above, we have made a series of observations, reasonings, and actions. Here are the latest {self.history_window} trajectory (at most) we have taken:
1693
+ <history>{self.history[-self.history_window :]}</history>
1694
+
1695
+ However, the task is not completed yet. As the task is partially observable, we may need to replan the task based on the current state of the browser if necessary.
1696
+ Now please carefully examine the current task planning schema, and our history actions, and then judge whether the task needs to be fundamentally replanned. If so, please provide a detailed replanned schema (including the restated overall task).
1697
+
1698
+ Your output should be in json format, including the following fields:
1699
+ - `if_need_replan`: bool, A boolean value indicating whether the task needs to be fundamentally replanned.
1700
+ - `replanned_schema`: str, The replanned schema for the task, which should not be changed too much compared with the original one. If the task does not need to be replanned, the value should be an empty string.
1701
+ """ # noqa: E501
1702
+ # Reset the history message of planning_agent.
1703
+ self.planning_agent.reset()
1704
+ resp = self.planning_agent.step(replanning_prompt)
1705
+ resp_dict = _parse_json_output(resp.msgs[0].content)
1706
+
1707
+ if_need_replan = resp_dict.get("if_need_replan", False)
1708
+ replanned_schema = resp_dict.get("replanned_schema", "")
1709
+
1710
+ if if_need_replan:
1711
+ return True, replanned_schema
1712
+ else:
1713
+ return False, replanned_schema
1714
+
1715
+ @dependencies_required("playwright")
1716
+ async def browse_url(
1717
+ self, task_prompt: str, start_url: str, round_limit: int = 12
1718
+ ) -> str:
1719
+ r"""A powerful toolkit which can simulate the browser interaction to
1720
+ solve the task which needs multi-step actions.
1721
+
1722
+ Args:
1723
+ task_prompt (str): The task prompt to solve.
1724
+ start_url (str): The start URL to visit.
1725
+ round_limit (int): The round limit to solve the task.
1726
+ (default: :obj:`12`).
1727
+
1728
+ Returns:
1729
+ str: The simulation result to the task.
1730
+ """
1731
+
1732
+ self._reset()
1733
+ task_completed = False
1734
+ detailed_plan = self._task_planning(task_prompt, start_url)
1735
+ logger.debug(f"Detailed plan: {detailed_plan}")
1736
+
1737
+ await self.browser.async_init()
1738
+ await self.browser.visit_page(start_url)
1739
+ for i in range(round_limit):
1740
+ observation, reasoning, action_code = await self.async_observe(
1741
+ task_prompt, detailed_plan
1742
+ )
1743
+ logger.debug(f"Observation: {observation}")
1744
+ logger.debug(f"Reasoning: {reasoning}")
1745
+ logger.debug(f"Action code: {action_code}")
1746
+
1747
+ if "stop" in action_code:
1748
+ task_completed = True
1749
+ trajectory_info = {
1750
+ "round": i,
1751
+ "observation": observation,
1752
+ "thought": reasoning,
1753
+ "action": action_code,
1754
+ "action_if_success": True,
1755
+ "info": None,
1756
+ "current_url": self.browser.get_url(),
1757
+ }
1758
+ self.history.append(trajectory_info)
1759
+ break
1760
+
1761
+ else:
1762
+ success, info = await self.async_act(action_code)
1763
+ if not success:
1764
+ logger.warning(f"Error while executing the action: {info}")
1765
+
1766
+ trajectory_info = {
1767
+ "round": i,
1768
+ "observation": observation,
1769
+ "thought": reasoning,
1770
+ "action": action_code,
1771
+ "action_if_success": success,
1772
+ "info": info,
1773
+ "current_url": self.browser.get_url(),
1774
+ }
1775
+ self.history.append(trajectory_info)
1776
+
1777
+ # replan the task if necessary
1778
+ if_need_replan, replanned_schema = self._task_replanning(
1779
+ task_prompt, detailed_plan
1780
+ )
1781
+ if if_need_replan:
1782
+ detailed_plan = replanned_schema
1783
+ logger.debug(f"Replanned schema: {replanned_schema}")
1784
+
1785
+ if not task_completed:
1786
+ simulation_result = f"""
1787
+ The task is not completed within the round limit. Please check
1788
+ the last round {self.history_window} information to see if
1789
+ there is any useful information:
1790
+ <history>{self.history[-self.history_window:]}</history>
1791
+ """
1792
+
1793
+ else:
1794
+ simulation_result = self._get_final_answer(task_prompt)
1795
+
1796
+ await self.browser.close()
1797
+ return simulation_result
1798
+
1799
+ def get_tools(self) -> List[FunctionTool]:
1800
+ return [FunctionTool(self.browse_url)]