camel-ai 0.2.60__py3-none-any.whl → 0.2.61__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.

@@ -18,9 +18,7 @@ from __future__ import annotations
18
18
  import asyncio
19
19
  import datetime
20
20
  import io
21
- import json
22
21
  import os
23
- import random
24
22
  import re
25
23
  import shutil
26
24
  import urllib.parse
@@ -28,19 +26,17 @@ from copy import deepcopy
28
26
  from typing import (
29
27
  TYPE_CHECKING,
30
28
  Any,
31
- BinaryIO,
32
29
  Coroutine,
33
30
  Dict,
34
31
  List,
35
32
  Literal,
36
33
  Optional,
37
34
  Tuple,
38
- TypedDict,
39
35
  Union,
40
36
  cast,
41
37
  )
42
38
 
43
- from PIL import Image, ImageDraw, ImageFont
39
+ from PIL import Image
44
40
 
45
41
  if TYPE_CHECKING:
46
42
  from camel.agents import ChatAgent
@@ -57,44 +53,25 @@ from camel.utils import (
57
53
  sanitize_filename,
58
54
  )
59
55
 
60
- logger = get_logger(__name__)
56
+ from .browser_toolkit_commons import (
57
+ ACTION_WITH_FEEDBACK_LIST,
58
+ AVAILABLE_ACTIONS_PROMPT,
59
+ GET_FINAL_ANSWER_PROMPT_TEMPLATE,
60
+ OBSERVE_PROMPT_TEMPLATE,
61
+ PLANNING_AGENT_SYSTEM_PROMPT,
62
+ TASK_PLANNING_PROMPT_TEMPLATE,
63
+ TASK_REPLANNING_PROMPT_TEMPLATE,
64
+ WEB_AGENT_SYSTEM_PROMPT,
65
+ InteractiveRegion,
66
+ VisualViewport,
67
+ _parse_json_output,
68
+ _reload_image,
69
+ add_set_of_mark,
70
+ interactive_region_from_dict,
71
+ visual_viewport_from_dict,
72
+ )
61
73
 
62
- TOP_NO_LABEL_ZONE = 20
63
-
64
- AVAILABLE_ACTIONS_PROMPT = """
65
- 1. `fill_input_id(identifier: Union[str, int], text: str)`: Fill an input
66
- field (e.g. search box) with the given text and press Enter.
67
- 2. `click_id(identifier: Union[str, int])`: Click an element with the given ID.
68
- 3. `hover_id(identifier: Union[str, int])`: Hover over an element with the
69
- given ID.
70
- 4. `download_file_id(identifier: Union[str, int])`: Download a file with the
71
- given ID. It returns the path to the downloaded file. If the file is
72
- successfully downloaded, you can stop the simulation and report the path to
73
- the downloaded file for further processing.
74
- 5. `scroll_to_bottom()`: Scroll to the bottom of the page.
75
- 6. `scroll_to_top()`: Scroll to the top of the page.
76
- 7. `scroll_up()`: Scroll up the page. It is suitable when you want to see the
77
- elements above the current viewport.
78
- 8. `scroll_down()`: Scroll down the page. It is suitable when you want to see
79
- the elements below the current viewport. If the webpage does not change, It
80
- means that the webpage has scrolled to the bottom.
81
- 9. `back()`: Navigate back to the previous page. This is useful when you want
82
- to go back to the previous page, as current page is not useful.
83
- 10. `stop()`: Stop the action process, because the task is completed or failed
84
- (impossible to find the answer). In this situation, you should provide your
85
- answer in your output.
86
- 11. `get_url()`: Get the current URL of the current page.
87
- 12. `find_text_on_page(search_text: str)`: Find the next given text on the
88
- current whole page, and scroll the page to the targeted text. It is equivalent
89
- to pressing Ctrl + F and searching for the text, and is powerful when you want
90
- to fast-check whether the current page contains some specific text.
91
- 13. `visit_page(url: str)`: Go to the specific url page.
92
- 14. `click_blank_area()`: Click a blank area of the page to unfocus the
93
- current element. It is useful when you have clicked an element but it cannot
94
- unfocus itself (e.g. Menu bar) to automatically render the updated webpage.
95
- 15. `ask_question_about_video(question: str)`: Ask a question about the
96
- current webpage which contains video, e.g. youtube websites.
97
- """
74
+ logger = get_logger(__name__)
98
75
 
99
76
  ASYNC_ACTIONS = [
100
77
  "fill_input_id",
@@ -112,46 +89,6 @@ ASYNC_ACTIONS = [
112
89
  "click_blank_area",
113
90
  ]
114
91
 
115
- ACTION_WITH_FEEDBACK_LIST = [
116
- 'ask_question_about_video',
117
- 'download_file_id',
118
- 'find_text_on_page',
119
- ]
120
-
121
-
122
- # Code from magentic-one
123
- class DOMRectangle(TypedDict):
124
- x: Union[int, float]
125
- y: Union[int, float]
126
- width: Union[int, float]
127
- height: Union[int, float]
128
- top: Union[int, float]
129
- right: Union[int, float]
130
- bottom: Union[int, float]
131
- left: Union[int, float]
132
-
133
-
134
- class VisualViewport(TypedDict):
135
- height: Union[int, float]
136
- width: Union[int, float]
137
- offsetLeft: Union[int, float]
138
- offsetTop: Union[int, float]
139
- pageLeft: Union[int, float]
140
- pageTop: Union[int, float]
141
- scale: Union[int, float]
142
- clientWidth: Union[int, float]
143
- clientHeight: Union[int, float]
144
- scrollWidth: Union[int, float]
145
- scrollHeight: Union[int, float]
146
-
147
-
148
- class InteractiveRegion(TypedDict):
149
- tag_name: str
150
- role: str
151
- aria_name: str
152
- v_scrollable: bool
153
- rects: List[DOMRectangle]
154
-
155
92
 
156
93
  def extract_function_name(s: str) -> str:
157
94
  r"""Extract the pure function name from a string (without parameters or
@@ -159,7 +96,7 @@ def extract_function_name(s: str) -> str:
159
96
 
160
97
  Args:
161
98
  s (str): Input string, e.g., `1.`**`click_id(14)`**, `scroll_up()`,
162
- `'visit_page(url)'`, etc.
99
+ `\'visit_page(url)\'`, etc.
163
100
 
164
101
  Returns:
165
102
  str: Pure function name (e.g., `click_id`, `scroll_up`, `visit_page`)
@@ -179,303 +116,6 @@ def extract_function_name(s: str) -> str:
179
116
  return re.split(r'[ (\n]', s, maxsplit=1)[0]
180
117
 
181
118
 
182
- def _get_str(d: Any, k: str) -> str:
183
- r"""Safely retrieve a string value from a dictionary."""
184
- if k not in d:
185
- raise KeyError(f"Missing required key: '{k}'")
186
- val = d[k]
187
- if isinstance(val, str):
188
- return val
189
- raise TypeError(
190
- f"Expected a string for key '{k}', " f"but got {type(val).__name__}"
191
- )
192
-
193
-
194
- def _get_number(d: Any, k: str) -> Union[int, float]:
195
- r"""Safely retrieve a number (int or float) from a dictionary"""
196
- val = d[k]
197
- if isinstance(val, (int, float)):
198
- return val
199
- raise TypeError(
200
- f"Expected a number (int/float) for key "
201
- f"'{k}', but got {type(val).__name__}"
202
- )
203
-
204
-
205
- def _get_bool(d: Any, k: str) -> bool:
206
- r"""Safely retrieve a boolean value from a dictionary."""
207
- val = d[k]
208
- if isinstance(val, bool):
209
- return val
210
- raise TypeError(
211
- f"Expected a boolean for key '{k}', " f"but got {type(val).__name__}"
212
- )
213
-
214
-
215
- def _parse_json_output(text: str) -> Dict[str, Any]:
216
- r"""Extract JSON output from a string."""
217
-
218
- markdown_pattern = r'```(?:json)?\s*(.*?)\s*```'
219
- markdown_match = re.search(markdown_pattern, text, re.DOTALL)
220
- if markdown_match:
221
- text = markdown_match.group(1).strip()
222
-
223
- triple_quotes_pattern = r'"""(?:json)?\s*(.*?)\s*"""'
224
- triple_quotes_match = re.search(triple_quotes_pattern, text, re.DOTALL)
225
- if triple_quotes_match:
226
- text = triple_quotes_match.group(1).strip()
227
-
228
- try:
229
- return json.loads(text)
230
- except json.JSONDecodeError:
231
- try:
232
- fixed_text = re.sub(
233
- r'`([^`]*?)`(?=\s*[:,\[\]{}]|$)', r'"\1"', text
234
- )
235
- return json.loads(fixed_text)
236
- except json.JSONDecodeError:
237
- result = {}
238
- try:
239
- bool_pattern = r'"(\w+)"\s*:\s*(true|false)'
240
- for match in re.finditer(bool_pattern, text, re.IGNORECASE):
241
- key, value = match.groups()
242
- result[key] = value.lower() == "true"
243
-
244
- str_pattern = r'"(\w+)"\s*:\s*"([^"]*)"'
245
- for match in re.finditer(str_pattern, text):
246
- key, value = match.groups()
247
- result[key] = value
248
-
249
- num_pattern = r'"(\w+)"\s*:\s*(-?\d+(?:\.\d+)?)'
250
- for match in re.finditer(num_pattern, text):
251
- key, value = match.groups()
252
- try:
253
- result[key] = int(value)
254
- except ValueError:
255
- result[key] = float(value)
256
-
257
- empty_str_pattern = r'"(\w+)"\s*:\s*""'
258
- for match in re.finditer(empty_str_pattern, text):
259
- key = match.group(1)
260
- result[key] = ""
261
-
262
- if result:
263
- return result
264
-
265
- logger.warning(f"Failed to parse JSON output: {text}")
266
- return {}
267
- except Exception as e:
268
- logger.warning(f"Error while extracting fields from JSON: {e}")
269
- return {}
270
-
271
-
272
- def _reload_image(image: Image.Image):
273
- buffer = io.BytesIO()
274
- image.save(buffer, format="PNG")
275
- buffer.seek(0)
276
- return Image.open(buffer)
277
-
278
-
279
- def dom_rectangle_from_dict(rect: Dict[str, Any]) -> DOMRectangle:
280
- r"""Create a DOMRectangle object from a dictionary."""
281
- return DOMRectangle(
282
- x=_get_number(rect, "x"),
283
- y=_get_number(rect, "y"),
284
- width=_get_number(rect, "width"),
285
- height=_get_number(rect, "height"),
286
- top=_get_number(rect, "top"),
287
- right=_get_number(rect, "right"),
288
- bottom=_get_number(rect, "bottom"),
289
- left=_get_number(rect, "left"),
290
- )
291
-
292
-
293
- def interactive_region_from_dict(region: Dict[str, Any]) -> InteractiveRegion:
294
- r"""Create an :class:`InteractiveRegion` object from a dictionary."""
295
- typed_rects: List[DOMRectangle] = []
296
- for rect in region["rects"]:
297
- typed_rects.append(dom_rectangle_from_dict(rect))
298
-
299
- return InteractiveRegion(
300
- tag_name=_get_str(region, "tag_name"),
301
- role=_get_str(region, "role"),
302
- aria_name=_get_str(region, "aria-name"),
303
- v_scrollable=_get_bool(region, "v-scrollable"),
304
- rects=typed_rects,
305
- )
306
-
307
-
308
- def visual_viewport_from_dict(viewport: Dict[str, Any]) -> VisualViewport:
309
- r"""Create a :class:`VisualViewport` object from a dictionary."""
310
- return VisualViewport(
311
- height=_get_number(viewport, "height"),
312
- width=_get_number(viewport, "width"),
313
- offsetLeft=_get_number(viewport, "offsetLeft"),
314
- offsetTop=_get_number(viewport, "offsetTop"),
315
- pageLeft=_get_number(viewport, "pageLeft"),
316
- pageTop=_get_number(viewport, "pageTop"),
317
- scale=_get_number(viewport, "scale"),
318
- clientWidth=_get_number(viewport, "clientWidth"),
319
- clientHeight=_get_number(viewport, "clientHeight"),
320
- scrollWidth=_get_number(viewport, "scrollWidth"),
321
- scrollHeight=_get_number(viewport, "scrollHeight"),
322
- )
323
-
324
-
325
- def add_set_of_mark(
326
- screenshot: Union[bytes, Image.Image, io.BufferedIOBase],
327
- ROIs: Dict[str, InteractiveRegion],
328
- ) -> Tuple[Image.Image, List[str], List[str], List[str]]:
329
- if isinstance(screenshot, Image.Image):
330
- return _add_set_of_mark(screenshot, ROIs)
331
-
332
- if isinstance(screenshot, bytes):
333
- screenshot = io.BytesIO(screenshot)
334
-
335
- image = Image.open(cast(BinaryIO, screenshot))
336
- comp, visible_rects, rects_above, rects_below = _add_set_of_mark(
337
- image, ROIs
338
- )
339
- image.close()
340
- return comp, visible_rects, rects_above, rects_below
341
-
342
-
343
- def _add_set_of_mark(
344
- screenshot: Image.Image, ROIs: Dict[str, InteractiveRegion]
345
- ) -> Tuple[Image.Image, List[str], List[str], List[str]]:
346
- r"""Add a set of marks to the screenshot.
347
-
348
- Args:
349
- screenshot (Image.Image): The screenshot to add marks to.
350
- ROIs (Dict[str, InteractiveRegion]): The regions to add marks to.
351
-
352
- Returns:
353
- Tuple[Image.Image, List[str], List[str], List[str]]: A tuple
354
- containing the screenshot with marked ROIs, ROIs fully within the
355
- images, ROIs located above the visible area, and ROIs located below
356
- the visible area.
357
- """
358
- visible_rects: List[str] = list()
359
- rects_above: List[str] = list() # Scroll up to see
360
- rects_below: List[str] = list() # Scroll down to see
361
-
362
- fnt = ImageFont.load_default(14)
363
- base = screenshot.convert("L").convert("RGBA")
364
- overlay = Image.new("RGBA", base.size)
365
-
366
- draw = ImageDraw.Draw(overlay)
367
- for r in ROIs:
368
- for rect in ROIs[r]["rects"]:
369
- # Empty rectangles
370
- if not rect or rect["width"] == 0 or rect["height"] == 0:
371
- continue
372
-
373
- # TODO: add scroll left and right?
374
- horizontal_center = (rect["right"] + rect["left"]) / 2.0
375
- vertical_center = (rect["top"] + rect["bottom"]) / 2.0
376
- is_within_horizon = 0 <= horizontal_center < base.size[0]
377
- is_above_viewport = vertical_center < 0
378
- is_below_viewport = vertical_center >= base.size[1]
379
-
380
- if is_within_horizon:
381
- if is_above_viewport:
382
- rects_above.append(r)
383
- elif is_below_viewport:
384
- rects_below.append(r)
385
- else: # Fully visible
386
- visible_rects.append(r)
387
- _draw_roi(draw, int(r), fnt, rect)
388
-
389
- comp = Image.alpha_composite(base, overlay)
390
- overlay.close()
391
- return comp, visible_rects, rects_above, rects_below
392
-
393
-
394
- def _draw_roi(
395
- draw: ImageDraw.ImageDraw,
396
- idx: int,
397
- font: ImageFont.FreeTypeFont | ImageFont.ImageFont,
398
- rect: DOMRectangle,
399
- ) -> None:
400
- r"""Draw a ROI on the image.
401
-
402
- Args:
403
- draw (ImageDraw.ImageDraw): The draw object.
404
- idx (int): The index of the ROI.
405
- font (ImageFont.FreeTypeFont | ImageFont.ImageFont): The font.
406
- rect (DOMRectangle): The DOM rectangle.
407
- """
408
- color = _get_random_color(idx)
409
- text_color = _get_text_color(color)
410
-
411
- roi = ((rect["left"], rect["top"]), (rect["right"], rect["bottom"]))
412
-
413
- label_location = (rect["right"], rect["top"])
414
- label_anchor = "rb"
415
-
416
- if label_location[1] <= TOP_NO_LABEL_ZONE:
417
- label_location = (rect["right"], rect["bottom"])
418
- label_anchor = "rt"
419
-
420
- draw.rectangle(
421
- roi, outline=color, fill=(color[0], color[1], color[2], 48), width=2
422
- )
423
-
424
- bbox = draw.textbbox(
425
- label_location,
426
- str(idx),
427
- font=font,
428
- anchor=label_anchor,
429
- align="center",
430
- )
431
- bbox = (bbox[0] - 3, bbox[1] - 3, bbox[2] + 3, bbox[3] + 3)
432
- draw.rectangle(bbox, fill=color)
433
-
434
- draw.text(
435
- label_location,
436
- str(idx),
437
- fill=text_color,
438
- font=font,
439
- anchor=label_anchor,
440
- align="center",
441
- )
442
-
443
-
444
- def _get_text_color(
445
- bg_color: Tuple[int, int, int, int],
446
- ) -> Tuple[int, int, int, int]:
447
- r"""Determine the ideal text color (black or white) for contrast.
448
-
449
- Args:
450
- bg_color: The background color (R, G, B, A).
451
-
452
- Returns:
453
- A tuple representing black or white color for text.
454
- """
455
- luminance = bg_color[0] * 0.3 + bg_color[1] * 0.59 + bg_color[2] * 0.11
456
- return (0, 0, 0, 255) if luminance > 120 else (255, 255, 255, 255)
457
-
458
-
459
- def _get_random_color(identifier: int) -> Tuple[int, int, int, int]:
460
- r"""Generate a consistent random RGBA color based on the identifier.
461
-
462
- Args:
463
- identifier: The ID used as a seed to ensure color consistency.
464
-
465
- Returns:
466
- A tuple representing (R, G, B, A) values.
467
- """
468
- rnd = random.Random(int(identifier))
469
- r = rnd.randint(0, 255)
470
- g = rnd.randint(125, 255)
471
- b = rnd.randint(0, 50)
472
- color = [r, g, b]
473
- # TODO: check why shuffle is needed?
474
- rnd.shuffle(color)
475
- color.append(255)
476
- return cast(Tuple[int, int, int, int], tuple(color))
477
-
478
-
479
119
  class AsyncBaseBrowser:
480
120
  def __init__(
481
121
  self,
@@ -505,12 +145,19 @@ class AsyncBaseBrowser:
505
145
  async_playwright,
506
146
  )
507
147
 
508
- self.history: list = []
148
+ self.history: list[Any] = []
509
149
  self.headless = headless
510
150
  self.channel = channel
511
151
  self.playwright = async_playwright()
512
- self.page_history: list = []
152
+ self.page_history: list[Any] = []
513
153
  self.cookie_json_path = cookie_json_path
154
+ self.playwright_server: Any = None
155
+ self.playwright_started: bool = False
156
+ self.browser: Any = None
157
+ self.context: Any = None
158
+ self.page: Any = None
159
+ self.page_url: str = ""
160
+ self.web_agent_model: Optional[BaseModelBackend] = None
514
161
 
515
162
  # Set the cache directory
516
163
  self.cache_dir = "tmp/" if cache_dir is None else cache_dir
@@ -631,7 +278,10 @@ class AsyncBaseBrowser:
631
278
  return "User cancelled the video analysis."
632
279
 
633
280
  model = None
634
- if hasattr(self, 'web_agent_model'):
281
+ if (
282
+ hasattr(self, 'web_agent_model')
283
+ and self.web_agent_model is not None
284
+ ):
635
285
  model = self.web_agent_model
636
286
 
637
287
  video_analyzer = VideoAnalysisToolkit(model=model)
@@ -723,7 +373,8 @@ class AsyncBaseBrowser:
723
373
  )
724
374
 
725
375
  _, file_path = await self.get_screenshot(save_image=True)
726
- screenshots.append(file_path)
376
+ if file_path is not None:
377
+ screenshots.append(file_path)
727
378
 
728
379
  await self.page.evaluate(f"window.scrollBy(0, {scroll_step})")
729
380
  # Allow time for content to load
@@ -800,7 +451,7 @@ class AsyncBaseBrowser:
800
451
  for k in result:
801
452
  typed_results[k] = interactive_region_from_dict(result[k])
802
453
 
803
- return typed_results # type: ignore[return-value]
454
+ return typed_results
804
455
 
805
456
  def get_interactive_elements(
806
457
  self,
@@ -830,13 +481,13 @@ class AsyncBaseBrowser:
830
481
  """
831
482
 
832
483
  await self.wait_for_load()
833
- screenshot, _ = await self.get_screenshot(save_image=False)
834
- rects = await self.get_interactive_elements()
484
+ screenshot, _ = await self.async_get_screenshot(save_image=False)
485
+ rects = await self.async_get_interactive_elements()
835
486
 
836
487
  file_path: str | None = None
837
488
  comp, _, _, _ = add_set_of_mark(
838
489
  screenshot,
839
- rects, # type: ignore[arg-type]
490
+ rects,
840
491
  )
841
492
  if save_image:
842
493
  parsed_url = urllib.parse.urlparse(self.page_url)
@@ -902,7 +553,7 @@ class AsyncBaseBrowser:
902
553
 
903
554
  try:
904
555
  await target.wait_for(timeout=5000)
905
- except (TimeoutError, Exception) as e:
556
+ except (TimeoutError, Exception) as e: # type: ignore[misc]
906
557
  logger.debug(f"Error during click operation: {e}")
907
558
  raise ValueError("No such element.") from None
908
559
 
@@ -926,7 +577,7 @@ class AsyncBaseBrowser:
926
577
  self.page_history.append(deepcopy(self.page.url))
927
578
  self.page = new_page
928
579
 
929
- except (TimeoutError, Exception) as e:
580
+ except (TimeoutError, Exception) as e: # type: ignore[misc]
930
581
  logger.debug(f"Error during click operation: {e}")
931
582
  pass
932
583
 
@@ -962,7 +613,7 @@ class AsyncBaseBrowser:
962
613
  identifier = str(identifier)
963
614
  try:
964
615
  target = self.page.locator(f"[__elementId='{identifier}']")
965
- except (TimeoutError, Exception) as e:
616
+ except (TimeoutError, Exception) as e: # type: ignore[misc]
966
617
  logger.debug(f"Error during download operation: {e}")
967
618
  logger.warning(
968
619
  f"Element with identifier '{identifier}' not found."
@@ -1015,7 +666,7 @@ class AsyncBaseBrowser:
1015
666
 
1016
667
  try:
1017
668
  target = self.page.locator(f"[__elementId='{identifier}']")
1018
- except (TimeoutError, Exception) as e:
669
+ except (TimeoutError, Exception) as e: # type: ignore[misc]
1019
670
  logger.debug(f"Error during fill operation: {e}")
1020
671
  logger.warning(
1021
672
  f"Element with identifier '{identifier}' not found."
@@ -1079,7 +730,7 @@ class AsyncBaseBrowser:
1079
730
  identifier = str(identifier)
1080
731
  try:
1081
732
  target = self.page.locator(f"[__elementId='{identifier}']")
1082
- except (TimeoutError, Exception) as e:
733
+ except (TimeoutError, Exception) as e: # type: ignore[misc]
1083
734
  logger.debug(f"Error during hover operation: {e}")
1084
735
  logger.warning(
1085
736
  f"Element with identifier '{identifier}' not found."
@@ -1316,7 +967,7 @@ class AsyncBrowserToolkit(BaseToolkit):
1316
967
  login.
1317
968
  (default: :obj:`None`)
1318
969
  """
1319
-
970
+ super().__init__()
1320
971
  self.browser = AsyncBaseBrowser(
1321
972
  headless=headless,
1322
973
  cache_dir=cache_dir,
@@ -1328,8 +979,9 @@ class AsyncBrowserToolkit(BaseToolkit):
1328
979
  self.web_agent_model = web_agent_model
1329
980
  self.planning_agent_model = planning_agent_model
1330
981
  self.output_language = output_language
982
+ self.browser.web_agent_model = web_agent_model
1331
983
 
1332
- self.history: list = []
984
+ self.history: list[Any] = []
1333
985
  self.web_agent, self.planning_agent = self._initialize_agent()
1334
986
 
1335
987
  def _reset(self):
@@ -1359,11 +1011,7 @@ class AsyncBrowserToolkit(BaseToolkit):
1359
1011
  else:
1360
1012
  planning_model = self.planning_agent_model
1361
1013
 
1362
- system_prompt = """
1363
- You are a helpful web agent that can assist users in browsing the web.
1364
- Given a high-level task, you can leverage predefined browser tools to help
1365
- users achieve their goals.
1366
- """
1014
+ system_prompt = WEB_AGENT_SYSTEM_PROMPT
1367
1015
 
1368
1016
  web_agent = ChatAgent(
1369
1017
  system_message=system_prompt,
@@ -1371,10 +1019,7 @@ users achieve their goals.
1371
1019
  output_language=self.output_language,
1372
1020
  )
1373
1021
 
1374
- planning_system_prompt = """
1375
- You are a helpful planning agent that can assist users in planning complex
1376
- tasks which need multi-step browser interaction.
1377
- """
1022
+ planning_system_prompt = PLANNING_AGENT_SYSTEM_PROMPT
1378
1023
 
1379
1024
  planning_agent = ChatAgent(
1380
1025
  system_message=planning_system_prompt,
@@ -1390,97 +1035,23 @@ tasks which need multi-step browser interaction.
1390
1035
  r"""Let agent observe the current environment, and get the next
1391
1036
  action."""
1392
1037
 
1393
- detailed_plan_prompt = ""
1038
+ detailed_plan_prompt_str = ""
1394
1039
 
1395
1040
  if detailed_plan is not None:
1396
- detailed_plan_prompt = f"""
1041
+ detailed_plan_prompt_str = f"""
1397
1042
  Here is a plan about how to solve the task step-by-step which you must follow:
1398
- <detailed_plan>{detailed_plan}<detailed_plan>
1043
+ <detailed_plan>{detailed_plan}</detailed_plan>
1399
1044
  """
1400
1045
 
1401
- observe_prompt = f"""
1402
- Please act as a web agent to help me complete the following high-level task:
1403
- <task>{task_prompt}</task>
1404
- Now, I have made screenshot (only the current viewport, not the full webpage)
1405
- based on the current browser state, and marked interactive elements in the
1406
- webpage.
1407
- Please carefully examine the requirements of the task, and current state of
1408
- the browser, and provide the next appropriate action to take.
1409
-
1410
- {detailed_plan_prompt}
1411
-
1412
- Here are the current available browser functions you can use:
1413
- {AVAILABLE_ACTIONS_PROMPT}
1414
-
1415
- Here are the latest {self.history_window} trajectory (at most) you have taken:
1416
- <history>
1417
- {self.history[-self.history_window :]}
1418
- </history>
1419
-
1420
- Your output should be in json format, including the following fields:
1421
- - `observation`: The detailed image description about the current viewport. Do
1422
- not over-confident about the correctness of the history actions. You should
1423
- always check the current viewport to make sure the correctness of the next
1424
- action.
1425
- - `reasoning`: The reasoning about the next action you want to take, and the
1426
- possible obstacles you may encounter, and how to solve them. Do not forget to
1427
- check the history actions to avoid the same mistakes.
1428
- - `action_code`: The action code you want to take. It is only one step action
1429
- code, without any other texts (such as annotation)
1430
-
1431
- Here is two example of the output:
1432
- ```json
1433
- {{
1434
- "observation": [IMAGE_DESCRIPTION],
1435
- "reasoning": [YOUR_REASONING],
1436
- "action_code": "fill_input_id([ID], [TEXT])"
1437
- }}
1438
-
1439
- {{
1440
- "observation": "The current page is a CAPTCHA verification page on Amazon. It asks the user to ..",
1441
- "reasoning": "To proceed with the task of searching for products, I need to complete..",
1442
- "action_code": "fill_input_id(3, 'AUXPMR')"
1443
- }}
1444
-
1445
- Here are some tips for you:
1446
- - Never forget the overall question: **{task_prompt}**
1447
- - Maybe after a certain operation (e.g. click_id), the page content has not
1448
- changed. You can check whether the action step is successful by looking at the
1449
- `success` of the action step in the history. If successful, it means that the
1450
- page content is indeed the same after the click. You need to try other methods.
1451
- - If using one way to solve the problem is not successful, try other ways.
1452
- Make sure your provided ID is correct!
1453
- - Some cases are very complex and need to be achieve by an iterative process.
1454
- You can use the `back()` function to go back to the previous page to try other
1455
- methods.
1456
- - There are many links on the page, which may be useful for solving the
1457
- problem. You can use the `click_id()` function to click on the link to see if
1458
- it is useful.
1459
- - Always keep in mind that your action must be based on the ID shown in the
1460
- current image or viewport, not the ID shown in the history.
1461
- - Do not use `stop()` lightly. Always remind yourself that the image only
1462
- shows a part of the full page. If you cannot find the answer, try to use
1463
- functions like `scroll_up()` and `scroll_down()` to check the full content of
1464
- the webpage before doing anything else, because the answer or next key step
1465
- may be hidden in the content below.
1466
- - If the webpage needs human verification, you must avoid processing it.
1467
- Please use `back()` to go back to the previous page, and try other ways.
1468
- - If you have tried everything and still cannot resolve the issue, please stop
1469
- the simulation, and report issues you have encountered.
1470
- - Check the history actions carefully, detect whether you have repeatedly made
1471
- the same actions or not.
1472
- - When dealing with wikipedia revision history related tasks, you need to
1473
- think about the solution flexibly. First, adjust the browsing history
1474
- displayed on a single page to the maximum, and then make use of the
1475
- find_text_on_page function. This is extremely useful which can quickly locate
1476
- the text you want to find and skip massive amount of useless information.
1477
- - Flexibly use interactive elements like slide down selection bar to filter
1478
- out the information you need. Sometimes they are extremely useful.
1479
- ```
1480
- """ # noqa: E501
1481
-
1046
+ observe_prompt = OBSERVE_PROMPT_TEMPLATE.format(
1047
+ task_prompt=task_prompt,
1048
+ detailed_plan_prompt=detailed_plan_prompt_str,
1049
+ AVAILABLE_ACTIONS_PROMPT=AVAILABLE_ACTIONS_PROMPT,
1050
+ history_window=self.history_window,
1051
+ history=self.history[-self.history_window :],
1052
+ )
1482
1053
  # get current state
1483
- som_screenshot, _ = await self.browser.get_som_screenshot(
1054
+ som_screenshot, _ = await self.browser.async_get_som_screenshot(
1484
1055
  save_image=True
1485
1056
  )
1486
1057
  img = _reload_image(som_screenshot)
@@ -1493,7 +1064,7 @@ out the information you need. Sometimes they are extremely useful.
1493
1064
 
1494
1065
  resp_content = resp.msgs[0].content
1495
1066
 
1496
- resp_dict = _parse_json_output(resp_content)
1067
+ resp_dict = _parse_json_output(resp_content, logger)
1497
1068
  observation_result: str = resp_dict.get("observation", "")
1498
1069
  reasoning_result: str = resp_dict.get("reasoning", "")
1499
1070
  action_code: str = resp_dict.get("action_code", "")
@@ -1632,12 +1203,9 @@ out the information you need. Sometimes they are extremely useful.
1632
1203
  current viewport.
1633
1204
  """
1634
1205
 
1635
- prompt = f"""
1636
- 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.
1637
- Here are all trajectory we have taken:
1638
- <history>{self.history}</history>
1639
- 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>
1640
- """ # noqa: E501
1206
+ prompt = GET_FINAL_ANSWER_PROMPT_TEMPLATE.format(
1207
+ history=self.history, task_prompt=task_prompt
1208
+ )
1641
1209
 
1642
1210
  message = BaseMessage.make_user_message(
1643
1211
  role_name='user',
@@ -1653,13 +1221,9 @@ Please find the final answer, or give valuable insights and founds (e.g. if prev
1653
1221
  # Here are the available browser functions we can
1654
1222
  # use: {AVAILABLE_ACTIONS_PROMPT}
1655
1223
 
1656
- planning_prompt = f"""
1657
- <task>{task_prompt}</task>
1658
- According to the problem above, if we use browser interaction, what is the general process of the interaction after visiting the webpage `{start_url}`?
1659
-
1660
- Please note that it can be viewed as Partially Observable MDP. Do not over-confident about your plan.
1661
- Please first restate the task in detail, and then provide a detailed plan to solve the task.
1662
- """ # noqa: E501
1224
+ planning_prompt = TASK_PLANNING_PROMPT_TEMPLATE.format(
1225
+ task_prompt=task_prompt, start_url=start_url
1226
+ )
1663
1227
 
1664
1228
  message = BaseMessage.make_user_message(
1665
1229
  role_name='user', content=planning_prompt
@@ -1685,28 +1249,16 @@ Please first restate the task in detail, and then provide a detailed plan to sol
1685
1249
 
1686
1250
  # Here are the available browser functions we can
1687
1251
  # use: {AVAILABLE_ACTIONS_PROMPT}
1688
- replanning_prompt = f"""
1689
- We are using browser interaction to solve a complex task which needs multi-step actions.
1690
- Here are the overall task:
1691
- <overall_task>{task_prompt}</overall_task>
1692
-
1693
- In order to solve the task, we made a detailed plan previously. Here is the detailed plan:
1694
- <detailed plan>{detailed_plan}</detailed plan>
1695
-
1696
- 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:
1697
- <history>{self.history[-self.history_window :]}</history>
1698
-
1699
- 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.
1700
- 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).
1701
-
1702
- Your output should be in json format, including the following fields:
1703
- - `if_need_replan`: bool, A boolean value indicating whether the task needs to be fundamentally replanned.
1704
- - `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.
1705
- """ # noqa: E501
1252
+ replanning_prompt = TASK_REPLANNING_PROMPT_TEMPLATE.format(
1253
+ task_prompt=task_prompt,
1254
+ detailed_plan=detailed_plan,
1255
+ history_window=self.history_window,
1256
+ history=self.history[-self.history_window :],
1257
+ )
1706
1258
  # Reset the history message of planning_agent.
1707
1259
  self.planning_agent.reset()
1708
1260
  resp = self.planning_agent.step(replanning_prompt)
1709
- resp_dict = _parse_json_output(resp.msgs[0].content)
1261
+ resp_dict = _parse_json_output(resp.msgs[0].content, logger)
1710
1262
 
1711
1263
  if_need_replan = resp_dict.get("if_need_replan", False)
1712
1264
  replanned_schema = resp_dict.get("replanned_schema", "")
@@ -1791,7 +1343,7 @@ Your output should be in json format, including the following fields:
1791
1343
  The task is not completed within the round limit. Please check
1792
1344
  the last round {self.history_window} information to see if
1793
1345
  there is any useful information:
1794
- <history>{self.history[-self.history_window:]}</history>
1346
+ <history>{self.history[-self.history_window :]}</history>
1795
1347
  """
1796
1348
 
1797
1349
  else: