camel-ai 0.2.59__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.

Files changed (55) hide show
  1. camel/__init__.py +1 -1
  2. camel/agents/chat_agent.py +158 -7
  3. camel/configs/anthropic_config.py +6 -5
  4. camel/configs/cohere_config.py +1 -1
  5. camel/configs/mistral_config.py +1 -1
  6. camel/configs/openai_config.py +3 -0
  7. camel/configs/reka_config.py +1 -1
  8. camel/configs/samba_config.py +2 -2
  9. camel/datagen/cot_datagen.py +29 -34
  10. camel/datagen/evol_instruct/scorer.py +22 -23
  11. camel/datagen/evol_instruct/templates.py +46 -46
  12. camel/datasets/static_dataset.py +144 -0
  13. camel/embeddings/jina_embedding.py +8 -1
  14. camel/embeddings/sentence_transformers_embeddings.py +2 -2
  15. camel/embeddings/vlm_embedding.py +9 -2
  16. camel/loaders/__init__.py +5 -2
  17. camel/loaders/chunkr_reader.py +117 -91
  18. camel/loaders/mistral_reader.py +148 -0
  19. camel/memories/blocks/chat_history_block.py +1 -2
  20. camel/memories/records.py +3 -0
  21. camel/messages/base.py +15 -3
  22. camel/models/azure_openai_model.py +1 -0
  23. camel/models/model_factory.py +2 -2
  24. camel/models/model_manager.py +7 -3
  25. camel/retrievers/bm25_retriever.py +1 -2
  26. camel/retrievers/hybrid_retrival.py +2 -2
  27. camel/societies/workforce/workforce.py +65 -24
  28. camel/storages/__init__.py +2 -0
  29. camel/storages/vectordb_storages/__init__.py +2 -0
  30. camel/storages/vectordb_storages/faiss.py +712 -0
  31. camel/storages/vectordb_storages/oceanbase.py +1 -2
  32. camel/toolkits/__init__.py +2 -0
  33. camel/toolkits/async_browser_toolkit.py +80 -524
  34. camel/toolkits/bohrium_toolkit.py +318 -0
  35. camel/toolkits/browser_toolkit.py +221 -541
  36. camel/toolkits/browser_toolkit_commons.py +568 -0
  37. camel/toolkits/dalle_toolkit.py +4 -0
  38. camel/toolkits/excel_toolkit.py +8 -2
  39. camel/toolkits/file_write_toolkit.py +76 -29
  40. camel/toolkits/github_toolkit.py +43 -25
  41. camel/toolkits/image_analysis_toolkit.py +3 -0
  42. camel/toolkits/jina_reranker_toolkit.py +194 -77
  43. camel/toolkits/mcp_toolkit.py +134 -16
  44. camel/toolkits/page_script.js +40 -28
  45. camel/toolkits/twitter_toolkit.py +6 -1
  46. camel/toolkits/video_analysis_toolkit.py +3 -0
  47. camel/toolkits/video_download_toolkit.py +3 -0
  48. camel/toolkits/wolfram_alpha_toolkit.py +51 -23
  49. camel/types/enums.py +27 -6
  50. camel/utils/__init__.py +2 -0
  51. camel/utils/commons.py +27 -0
  52. {camel_ai-0.2.59.dist-info → camel_ai-0.2.61.dist-info}/METADATA +17 -9
  53. {camel_ai-0.2.59.dist-info → camel_ai-0.2.61.dist-info}/RECORD +55 -51
  54. {camel_ai-0.2.59.dist-info → camel_ai-0.2.61.dist-info}/WHEEL +0 -0
  55. {camel_ai-0.2.59.dist-info → camel_ai-0.2.61.dist-info}/licenses/LICENSE +0 -0
@@ -11,12 +11,14 @@
11
11
  # See the License for the specific language governing permissions and
12
12
  # limitations under the License.
13
13
  # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
+
15
+ # Enables postponed evaluation of annotations (for string-based type hints)
16
+ from __future__ import annotations
17
+
14
18
  import asyncio
15
19
  import datetime
16
20
  import io
17
- import json
18
21
  import os
19
- import random
20
22
  import re
21
23
  import shutil
22
24
  import urllib.parse
@@ -24,19 +26,17 @@ from copy import deepcopy
24
26
  from typing import (
25
27
  TYPE_CHECKING,
26
28
  Any,
27
- BinaryIO,
28
29
  Coroutine,
29
30
  Dict,
30
31
  List,
31
32
  Literal,
32
33
  Optional,
33
34
  Tuple,
34
- TypedDict,
35
35
  Union,
36
36
  cast,
37
37
  )
38
38
 
39
- from PIL import Image, ImageDraw, ImageFont
39
+ from PIL import Image
40
40
 
41
41
  if TYPE_CHECKING:
42
42
  from camel.agents import ChatAgent
@@ -53,44 +53,25 @@ from camel.utils import (
53
53
  sanitize_filename,
54
54
  )
55
55
 
56
- 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
+ )
57
73
 
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
- """
74
+ logger = get_logger(__name__)
94
75
 
95
76
  ASYNC_ACTIONS = [
96
77
  "fill_input_id",
@@ -108,46 +89,6 @@ ASYNC_ACTIONS = [
108
89
  "click_blank_area",
109
90
  ]
110
91
 
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
92
 
152
93
  def extract_function_name(s: str) -> str:
153
94
  r"""Extract the pure function name from a string (without parameters or
@@ -155,7 +96,7 @@ def extract_function_name(s: str) -> str:
155
96
 
156
97
  Args:
157
98
  s (str): Input string, e.g., `1.`**`click_id(14)`**, `scroll_up()`,
158
- `'visit_page(url)'`, etc.
99
+ `\'visit_page(url)\'`, etc.
159
100
 
160
101
  Returns:
161
102
  str: Pure function name (e.g., `click_id`, `scroll_up`, `visit_page`)
@@ -175,303 +116,6 @@ def extract_function_name(s: str) -> str:
175
116
  return re.split(r'[ (\n]', s, maxsplit=1)[0]
176
117
 
177
118
 
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
119
  class AsyncBaseBrowser:
476
120
  def __init__(
477
121
  self,
@@ -501,12 +145,19 @@ class AsyncBaseBrowser:
501
145
  async_playwright,
502
146
  )
503
147
 
504
- self.history: list = []
148
+ self.history: list[Any] = []
505
149
  self.headless = headless
506
150
  self.channel = channel
507
151
  self.playwright = async_playwright()
508
- self.page_history: list = []
152
+ self.page_history: list[Any] = []
509
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
510
161
 
511
162
  # Set the cache directory
512
163
  self.cache_dir = "tmp/" if cache_dir is None else cache_dir
@@ -627,7 +278,10 @@ class AsyncBaseBrowser:
627
278
  return "User cancelled the video analysis."
628
279
 
629
280
  model = None
630
- if hasattr(self, 'web_agent_model'):
281
+ if (
282
+ hasattr(self, 'web_agent_model')
283
+ and self.web_agent_model is not None
284
+ ):
631
285
  model = self.web_agent_model
632
286
 
633
287
  video_analyzer = VideoAnalysisToolkit(model=model)
@@ -719,7 +373,8 @@ class AsyncBaseBrowser:
719
373
  )
720
374
 
721
375
  _, file_path = await self.get_screenshot(save_image=True)
722
- screenshots.append(file_path)
376
+ if file_path is not None:
377
+ screenshots.append(file_path)
723
378
 
724
379
  await self.page.evaluate(f"window.scrollBy(0, {scroll_step})")
725
380
  # Allow time for content to load
@@ -796,7 +451,7 @@ class AsyncBaseBrowser:
796
451
  for k in result:
797
452
  typed_results[k] = interactive_region_from_dict(result[k])
798
453
 
799
- return typed_results # type: ignore[return-value]
454
+ return typed_results
800
455
 
801
456
  def get_interactive_elements(
802
457
  self,
@@ -826,13 +481,13 @@ class AsyncBaseBrowser:
826
481
  """
827
482
 
828
483
  await self.wait_for_load()
829
- screenshot, _ = await self.get_screenshot(save_image=False)
830
- rects = await self.get_interactive_elements()
484
+ screenshot, _ = await self.async_get_screenshot(save_image=False)
485
+ rects = await self.async_get_interactive_elements()
831
486
 
832
487
  file_path: str | None = None
833
488
  comp, _, _, _ = add_set_of_mark(
834
489
  screenshot,
835
- rects, # type: ignore[arg-type]
490
+ rects,
836
491
  )
837
492
  if save_image:
838
493
  parsed_url = urllib.parse.urlparse(self.page_url)
@@ -898,7 +553,7 @@ class AsyncBaseBrowser:
898
553
 
899
554
  try:
900
555
  await target.wait_for(timeout=5000)
901
- except (TimeoutError, Exception) as e:
556
+ except (TimeoutError, Exception) as e: # type: ignore[misc]
902
557
  logger.debug(f"Error during click operation: {e}")
903
558
  raise ValueError("No such element.") from None
904
559
 
@@ -922,7 +577,7 @@ class AsyncBaseBrowser:
922
577
  self.page_history.append(deepcopy(self.page.url))
923
578
  self.page = new_page
924
579
 
925
- except (TimeoutError, Exception) as e:
580
+ except (TimeoutError, Exception) as e: # type: ignore[misc]
926
581
  logger.debug(f"Error during click operation: {e}")
927
582
  pass
928
583
 
@@ -958,7 +613,7 @@ class AsyncBaseBrowser:
958
613
  identifier = str(identifier)
959
614
  try:
960
615
  target = self.page.locator(f"[__elementId='{identifier}']")
961
- except (TimeoutError, Exception) as e:
616
+ except (TimeoutError, Exception) as e: # type: ignore[misc]
962
617
  logger.debug(f"Error during download operation: {e}")
963
618
  logger.warning(
964
619
  f"Element with identifier '{identifier}' not found."
@@ -1011,7 +666,7 @@ class AsyncBaseBrowser:
1011
666
 
1012
667
  try:
1013
668
  target = self.page.locator(f"[__elementId='{identifier}']")
1014
- except (TimeoutError, Exception) as e:
669
+ except (TimeoutError, Exception) as e: # type: ignore[misc]
1015
670
  logger.debug(f"Error during fill operation: {e}")
1016
671
  logger.warning(
1017
672
  f"Element with identifier '{identifier}' not found."
@@ -1075,7 +730,7 @@ class AsyncBaseBrowser:
1075
730
  identifier = str(identifier)
1076
731
  try:
1077
732
  target = self.page.locator(f"[__elementId='{identifier}']")
1078
- except (TimeoutError, Exception) as e:
733
+ except (TimeoutError, Exception) as e: # type: ignore[misc]
1079
734
  logger.debug(f"Error during hover operation: {e}")
1080
735
  logger.warning(
1081
736
  f"Element with identifier '{identifier}' not found."
@@ -1312,7 +967,7 @@ class AsyncBrowserToolkit(BaseToolkit):
1312
967
  login.
1313
968
  (default: :obj:`None`)
1314
969
  """
1315
-
970
+ super().__init__()
1316
971
  self.browser = AsyncBaseBrowser(
1317
972
  headless=headless,
1318
973
  cache_dir=cache_dir,
@@ -1324,8 +979,9 @@ class AsyncBrowserToolkit(BaseToolkit):
1324
979
  self.web_agent_model = web_agent_model
1325
980
  self.planning_agent_model = planning_agent_model
1326
981
  self.output_language = output_language
982
+ self.browser.web_agent_model = web_agent_model
1327
983
 
1328
- self.history: list = []
984
+ self.history: list[Any] = []
1329
985
  self.web_agent, self.planning_agent = self._initialize_agent()
1330
986
 
1331
987
  def _reset(self):
@@ -1336,7 +992,7 @@ class AsyncBrowserToolkit(BaseToolkit):
1336
992
 
1337
993
  def _initialize_agent(self) -> Tuple["ChatAgent", "ChatAgent"]:
1338
994
  r"""Initialize the agent."""
1339
- from camel.agents import ChatAgent
995
+ from camel.agents.chat_agent import ChatAgent
1340
996
 
1341
997
  if self.web_agent_model is None:
1342
998
  web_agent_model = ModelFactory.create(
@@ -1355,11 +1011,7 @@ class AsyncBrowserToolkit(BaseToolkit):
1355
1011
  else:
1356
1012
  planning_model = self.planning_agent_model
1357
1013
 
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
- """
1014
+ system_prompt = WEB_AGENT_SYSTEM_PROMPT
1363
1015
 
1364
1016
  web_agent = ChatAgent(
1365
1017
  system_message=system_prompt,
@@ -1367,10 +1019,7 @@ users achieve their goals.
1367
1019
  output_language=self.output_language,
1368
1020
  )
1369
1021
 
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
- """
1022
+ planning_system_prompt = PLANNING_AGENT_SYSTEM_PROMPT
1374
1023
 
1375
1024
  planning_agent = ChatAgent(
1376
1025
  system_message=planning_system_prompt,
@@ -1386,97 +1035,23 @@ tasks which need multi-step browser interaction.
1386
1035
  r"""Let agent observe the current environment, and get the next
1387
1036
  action."""
1388
1037
 
1389
- detailed_plan_prompt = ""
1038
+ detailed_plan_prompt_str = ""
1390
1039
 
1391
1040
  if detailed_plan is not None:
1392
- detailed_plan_prompt = f"""
1041
+ detailed_plan_prompt_str = f"""
1393
1042
  Here is a plan about how to solve the task step-by-step which you must follow:
1394
- <detailed_plan>{detailed_plan}<detailed_plan>
1043
+ <detailed_plan>{detailed_plan}</detailed_plan>
1395
1044
  """
1396
1045
 
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
-
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
+ )
1478
1053
  # get current state
1479
- som_screenshot, _ = await self.browser.get_som_screenshot(
1054
+ som_screenshot, _ = await self.browser.async_get_som_screenshot(
1480
1055
  save_image=True
1481
1056
  )
1482
1057
  img = _reload_image(som_screenshot)
@@ -1489,7 +1064,7 @@ out the information you need. Sometimes they are extremely useful.
1489
1064
 
1490
1065
  resp_content = resp.msgs[0].content
1491
1066
 
1492
- resp_dict = _parse_json_output(resp_content)
1067
+ resp_dict = _parse_json_output(resp_content, logger)
1493
1068
  observation_result: str = resp_dict.get("observation", "")
1494
1069
  reasoning_result: str = resp_dict.get("reasoning", "")
1495
1070
  action_code: str = resp_dict.get("action_code", "")
@@ -1628,12 +1203,9 @@ out the information you need. Sometimes they are extremely useful.
1628
1203
  current viewport.
1629
1204
  """
1630
1205
 
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
1206
+ prompt = GET_FINAL_ANSWER_PROMPT_TEMPLATE.format(
1207
+ history=self.history, task_prompt=task_prompt
1208
+ )
1637
1209
 
1638
1210
  message = BaseMessage.make_user_message(
1639
1211
  role_name='user',
@@ -1649,13 +1221,9 @@ Please find the final answer, or give valuable insights and founds (e.g. if prev
1649
1221
  # Here are the available browser functions we can
1650
1222
  # use: {AVAILABLE_ACTIONS_PROMPT}
1651
1223
 
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
1224
+ planning_prompt = TASK_PLANNING_PROMPT_TEMPLATE.format(
1225
+ task_prompt=task_prompt, start_url=start_url
1226
+ )
1659
1227
 
1660
1228
  message = BaseMessage.make_user_message(
1661
1229
  role_name='user', content=planning_prompt
@@ -1681,28 +1249,16 @@ Please first restate the task in detail, and then provide a detailed plan to sol
1681
1249
 
1682
1250
  # Here are the available browser functions we can
1683
1251
  # 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
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
+ )
1702
1258
  # Reset the history message of planning_agent.
1703
1259
  self.planning_agent.reset()
1704
1260
  resp = self.planning_agent.step(replanning_prompt)
1705
- resp_dict = _parse_json_output(resp.msgs[0].content)
1261
+ resp_dict = _parse_json_output(resp.msgs[0].content, logger)
1706
1262
 
1707
1263
  if_need_replan = resp_dict.get("if_need_replan", False)
1708
1264
  replanned_schema = resp_dict.get("replanned_schema", "")
@@ -1787,7 +1343,7 @@ Your output should be in json format, including the following fields:
1787
1343
  The task is not completed within the round limit. Please check
1788
1344
  the last round {self.history_window} information to see if
1789
1345
  there is any useful information:
1790
- <history>{self.history[-self.history_window:]}</history>
1346
+ <history>{self.history[-self.history_window :]}</history>
1791
1347
  """
1792
1348
 
1793
1349
  else: