camel-ai 0.2.22__py3-none-any.whl → 0.2.23__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 (110) hide show
  1. camel/__init__.py +1 -1
  2. camel/agents/_types.py +41 -0
  3. camel/agents/_utils.py +188 -0
  4. camel/agents/chat_agent.py +570 -965
  5. camel/agents/knowledge_graph_agent.py +7 -1
  6. camel/agents/multi_hop_generator_agent.py +1 -1
  7. camel/configs/base_config.py +10 -13
  8. camel/configs/deepseek_config.py +4 -30
  9. camel/configs/gemini_config.py +5 -31
  10. camel/configs/openai_config.py +14 -32
  11. camel/configs/qwen_config.py +36 -36
  12. camel/datagen/self_improving_cot.py +81 -3
  13. camel/datagen/self_instruct/filter/instruction_filter.py +19 -3
  14. camel/datagen/self_instruct/self_instruct.py +52 -3
  15. camel/datasets/__init__.py +28 -0
  16. camel/datasets/base.py +969 -0
  17. camel/environments/__init__.py +16 -0
  18. camel/environments/base.py +503 -0
  19. camel/extractors/__init__.py +16 -0
  20. camel/extractors/base.py +263 -0
  21. camel/memories/agent_memories.py +16 -1
  22. camel/memories/blocks/chat_history_block.py +10 -2
  23. camel/memories/blocks/vectordb_block.py +1 -0
  24. camel/memories/context_creators/score_based.py +20 -3
  25. camel/memories/records.py +10 -0
  26. camel/messages/base.py +8 -8
  27. camel/models/__init__.py +2 -0
  28. camel/models/_utils.py +57 -0
  29. camel/models/aiml_model.py +48 -17
  30. camel/models/anthropic_model.py +41 -3
  31. camel/models/azure_openai_model.py +39 -3
  32. camel/models/base_audio_model.py +92 -0
  33. camel/models/base_model.py +88 -13
  34. camel/models/cohere_model.py +88 -11
  35. camel/models/deepseek_model.py +107 -45
  36. camel/models/fish_audio_model.py +18 -8
  37. camel/models/gemini_model.py +133 -15
  38. camel/models/groq_model.py +72 -10
  39. camel/models/internlm_model.py +14 -3
  40. camel/models/litellm_model.py +9 -2
  41. camel/models/mistral_model.py +42 -5
  42. camel/models/model_manager.py +57 -3
  43. camel/models/moonshot_model.py +33 -4
  44. camel/models/nemotron_model.py +32 -3
  45. camel/models/nvidia_model.py +43 -3
  46. camel/models/ollama_model.py +139 -17
  47. camel/models/openai_audio_models.py +87 -2
  48. camel/models/openai_compatible_model.py +37 -3
  49. camel/models/openai_model.py +158 -46
  50. camel/models/qwen_model.py +61 -4
  51. camel/models/reka_model.py +53 -3
  52. camel/models/samba_model.py +209 -4
  53. camel/models/sglang_model.py +153 -14
  54. camel/models/siliconflow_model.py +16 -3
  55. camel/models/stub_model.py +46 -4
  56. camel/models/togetherai_model.py +38 -3
  57. camel/models/vllm_model.py +37 -3
  58. camel/models/yi_model.py +36 -3
  59. camel/models/zhipuai_model.py +38 -3
  60. camel/retrievers/__init__.py +3 -0
  61. camel/retrievers/hybrid_retrival.py +237 -0
  62. camel/toolkits/__init__.py +15 -1
  63. camel/toolkits/arxiv_toolkit.py +2 -1
  64. camel/toolkits/ask_news_toolkit.py +4 -2
  65. camel/toolkits/audio_analysis_toolkit.py +238 -0
  66. camel/toolkits/base.py +22 -3
  67. camel/toolkits/code_execution.py +2 -0
  68. camel/toolkits/dappier_toolkit.py +2 -1
  69. camel/toolkits/data_commons_toolkit.py +38 -12
  70. camel/toolkits/excel_toolkit.py +172 -0
  71. camel/toolkits/function_tool.py +13 -0
  72. camel/toolkits/github_toolkit.py +5 -1
  73. camel/toolkits/google_maps_toolkit.py +2 -1
  74. camel/toolkits/google_scholar_toolkit.py +2 -0
  75. camel/toolkits/human_toolkit.py +0 -3
  76. camel/toolkits/image_analysis_toolkit.py +202 -0
  77. camel/toolkits/linkedin_toolkit.py +3 -2
  78. camel/toolkits/meshy_toolkit.py +3 -2
  79. camel/toolkits/mineru_toolkit.py +2 -2
  80. camel/toolkits/networkx_toolkit.py +240 -0
  81. camel/toolkits/notion_toolkit.py +2 -0
  82. camel/toolkits/openbb_toolkit.py +3 -2
  83. camel/toolkits/page_script.js +376 -0
  84. camel/toolkits/reddit_toolkit.py +11 -3
  85. camel/toolkits/retrieval_toolkit.py +6 -1
  86. camel/toolkits/semantic_scholar_toolkit.py +2 -1
  87. camel/toolkits/stripe_toolkit.py +8 -2
  88. camel/toolkits/sympy_toolkit.py +6 -1
  89. camel/toolkits/video_analysis_toolkit.py +407 -0
  90. camel/toolkits/{video_toolkit.py → video_download_toolkit.py} +21 -25
  91. camel/toolkits/web_toolkit.py +1307 -0
  92. camel/toolkits/whatsapp_toolkit.py +3 -2
  93. camel/toolkits/zapier_toolkit.py +191 -0
  94. camel/types/__init__.py +2 -2
  95. camel/types/agents/__init__.py +16 -0
  96. camel/types/agents/tool_calling_record.py +52 -0
  97. camel/types/enums.py +3 -0
  98. camel/types/openai_types.py +16 -14
  99. camel/utils/__init__.py +2 -1
  100. camel/utils/async_func.py +2 -2
  101. camel/utils/commons.py +114 -1
  102. camel/verifiers/__init__.py +23 -0
  103. camel/verifiers/base.py +340 -0
  104. camel/verifiers/models.py +82 -0
  105. camel/verifiers/python_verifier.py +202 -0
  106. camel_ai-0.2.23.dist-info/METADATA +671 -0
  107. {camel_ai-0.2.22.dist-info → camel_ai-0.2.23.dist-info}/RECORD +122 -97
  108. {camel_ai-0.2.22.dist-info → camel_ai-0.2.23.dist-info}/WHEEL +1 -1
  109. camel_ai-0.2.22.dist-info/METADATA +0 -527
  110. {camel_ai-0.2.22.dist-info → camel_ai-0.2.23.dist-info/licenses}/LICENSE +0 -0
@@ -0,0 +1,1307 @@
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
+
15
+ import datetime
16
+ import io
17
+ import json
18
+ import os
19
+ import random
20
+ import re
21
+ import shutil
22
+ import time
23
+ from copy import deepcopy
24
+ from typing import (
25
+ TYPE_CHECKING,
26
+ Any,
27
+ BinaryIO,
28
+ Dict,
29
+ List,
30
+ Optional,
31
+ Tuple,
32
+ TypedDict,
33
+ Union,
34
+ cast,
35
+ )
36
+
37
+ from PIL import Image, ImageDraw, ImageFont
38
+
39
+ if TYPE_CHECKING:
40
+ from camel.agents import ChatAgent
41
+ from camel.logger import get_logger
42
+ from camel.messages import BaseMessage
43
+ from camel.models import BaseModelBackend, ModelFactory
44
+ from camel.toolkits import FunctionTool, VideoAnalysisToolkit
45
+ from camel.toolkits.base import BaseToolkit
46
+ from camel.types import ModelPlatformType, ModelType
47
+ from camel.utils import dependencies_required, retry_on_error
48
+
49
+ logger = get_logger(__name__)
50
+
51
+ TOP_NO_LABEL_ZONE = 20
52
+
53
+ AVAILABLE_ACTIONS_PROMPT = """
54
+ 1. `fill_input_id(identifier: Union[str, int], text: str)`: Fill an input
55
+ field (e.g. search box) with the given text and press Enter.
56
+ 2. `click_id(identifier: Union[str, int])`: Click an element with the given ID.
57
+ 3. `hover_id(identifier: Union[str, int])`: Hover over an element with the
58
+ given ID.
59
+ 4. `download_file_id(identifier: Union[str, int])`: Download a file with the
60
+ given ID. It returns the path to the downloaded file. If the file is
61
+ successfully downloaded, you can stop the simulation and report the path to
62
+ the downloaded file for further processing.
63
+ 5. `scroll_to_bottom()`: Scroll to the bottom of the page.
64
+ 6. `scroll_to_top()`: Scroll to the top of the page.
65
+ 7. `scroll_up()`: Scroll up the page. It is suitable when you want to see the
66
+ elements above the current viewport.
67
+ 8. `scroll_down()`: Scroll down the page. It is suitable when you want to see
68
+ the elements below the current viewport. If the webpage does not change, It
69
+ means that the webpage has scrolled to the bottom.
70
+ 9. `back()`: Navigate back to the previous page. This is useful when you want
71
+ to go back to the previous page, as current page is not useful.
72
+ 10. `stop()`: Stop the action process, because the task is completed or failed
73
+ (impossible to find the answer). In this situation, you should provide your
74
+ answer in your output.
75
+ 11. `get_url()`: Get the current URL of the current page.
76
+ 12. `find_text_on_page(search_text: str)`: Find the next given text on the
77
+ current whole page, and scroll the page to the targeted text. It is equivalent
78
+ to pressing Ctrl + F and searching for the text, and is powerful when you want
79
+ to fast-check whether the current page contains some specific text.
80
+ 13. `visit_page(url: str)`: Go to the specific url page.
81
+ 14. `click_blank_area()`: Click a blank area of the page to unfocus the
82
+ current element. It is useful when you have clicked an element but it cannot
83
+ unfocus itself (e.g. Menu bar) to automatically render the updated webpage.
84
+ 15. `ask_question_about_video(question: str)`: Ask a question about the
85
+ current webpage which contains video, e.g. youtube websites.
86
+ """
87
+
88
+ ACTION_WITH_FEEDBACK_LIST = [
89
+ 'ask_question_about_video',
90
+ 'download_file_id',
91
+ 'find_text_on_page',
92
+ ]
93
+
94
+
95
+ # codes from magentic-one
96
+ class DOMRectangle(TypedDict):
97
+ x: Union[int, float]
98
+ y: Union[int, float]
99
+ width: Union[int, float]
100
+ height: Union[int, float]
101
+ top: Union[int, float]
102
+ right: Union[int, float]
103
+ bottom: Union[int, float]
104
+ left: Union[int, float]
105
+
106
+
107
+ class VisualViewport(TypedDict):
108
+ height: Union[int, float]
109
+ width: Union[int, float]
110
+ offsetLeft: Union[int, float]
111
+ offsetTop: Union[int, float]
112
+ pageLeft: Union[int, float]
113
+ pageTop: Union[int, float]
114
+ scale: Union[int, float]
115
+ clientWidth: Union[int, float]
116
+ clientHeight: Union[int, float]
117
+ scrollWidth: Union[int, float]
118
+ scrollHeight: Union[int, float]
119
+
120
+
121
+ class InteractiveRegion(TypedDict):
122
+ tag_name: str
123
+ role: str
124
+ aria_name: str
125
+ v_scrollable: bool
126
+ rects: List[DOMRectangle]
127
+
128
+
129
+ def _get_str(d: Any, k: str) -> str:
130
+ val = d[k]
131
+ assert isinstance(val, str)
132
+ return val
133
+
134
+
135
+ def _get_number(d: Any, k: str) -> Union[int, float]:
136
+ val = d[k]
137
+ assert isinstance(val, int) or isinstance(val, float)
138
+ return val
139
+
140
+
141
+ def _get_bool(d: Any, k: str) -> bool:
142
+ val = d[k]
143
+ assert isinstance(val, bool)
144
+ return val
145
+
146
+
147
+ def _parse_json_output(text: str) -> Dict[str, Any]:
148
+ r"""Extract JSON output from a string."""
149
+
150
+ markdown_pattern = r'```(?:json)?\s*(.*?)\s*```'
151
+ markdown_match = re.search(markdown_pattern, text, re.DOTALL)
152
+ if markdown_match:
153
+ text = markdown_match.group(1).strip()
154
+
155
+ triple_quotes_pattern = r'"""(?:json)?\s*(.*?)\s*"""'
156
+ triple_quotes_match = re.search(triple_quotes_pattern, text, re.DOTALL)
157
+ if triple_quotes_match:
158
+ text = triple_quotes_match.group(1).strip()
159
+
160
+ text = text.replace("`", '"')
161
+
162
+ try:
163
+ return json.loads(text)
164
+ except json.JSONDecodeError:
165
+ try:
166
+ fixed_text = re.sub(r'`([^`]*)`', r'"\1"', text)
167
+ return json.loads(fixed_text)
168
+ except json.JSONDecodeError:
169
+ # Try to extract key fields
170
+ result = {}
171
+ try:
172
+ bool_pattern = r'"(\w+)"\s*:\s*(true|false)'
173
+ for match in re.finditer(bool_pattern, text, re.IGNORECASE):
174
+ key, value = match.groups()
175
+ result[key] = value.lower() == "true"
176
+
177
+ str_pattern = r'"(\w+)"\s*:\s*"([^"]*)"'
178
+ for match in re.finditer(str_pattern, text):
179
+ key, value = match.groups()
180
+ result[key] = value
181
+
182
+ num_pattern = r'"(\w+)"\s*:\s*(-?\d+(?:\.\d+)?)'
183
+ for match in re.finditer(num_pattern, text):
184
+ key, value = match.groups()
185
+ try:
186
+ result[key] = int(value)
187
+ except ValueError:
188
+ result[key] = float(value)
189
+
190
+ empty_str_pattern = r'"(\w+)"\s*:\s*""'
191
+ for match in re.finditer(empty_str_pattern, text):
192
+ key = match.group(1)
193
+ result[key] = ""
194
+
195
+ if result:
196
+ return result
197
+
198
+ logger.warning(f"Failed to parse JSON output: {text}")
199
+ return {}
200
+ except Exception as e:
201
+ logger.warning(f"Error while extracting fields from JSON: {e}")
202
+ return {}
203
+
204
+
205
+ def _reload_image(image: Image.Image):
206
+ buffer = io.BytesIO()
207
+ image.save(buffer, format="PNG")
208
+ buffer.seek(0)
209
+ return Image.open(buffer)
210
+
211
+
212
+ def domrectangle_from_dict(rect: Dict[str, Any]) -> DOMRectangle:
213
+ return DOMRectangle(
214
+ x=_get_number(rect, "x"),
215
+ y=_get_number(rect, "y"),
216
+ width=_get_number(rect, "width"),
217
+ height=_get_number(rect, "height"),
218
+ top=_get_number(rect, "top"),
219
+ right=_get_number(rect, "right"),
220
+ bottom=_get_number(rect, "bottom"),
221
+ left=_get_number(rect, "left"),
222
+ )
223
+
224
+
225
+ def interactiveregion_from_dict(region: Dict[str, Any]) -> InteractiveRegion:
226
+ typed_rects: List[DOMRectangle] = []
227
+ for rect in region["rects"]:
228
+ typed_rects.append(domrectangle_from_dict(rect))
229
+
230
+ return InteractiveRegion(
231
+ tag_name=_get_str(region, "tag_name"),
232
+ role=_get_str(region, "role"),
233
+ aria_name=_get_str(region, "aria-name"),
234
+ v_scrollable=_get_bool(region, "v-scrollable"),
235
+ rects=typed_rects,
236
+ )
237
+
238
+
239
+ def visualviewport_from_dict(viewport: Dict[str, Any]) -> VisualViewport:
240
+ return VisualViewport(
241
+ height=_get_number(viewport, "height"),
242
+ width=_get_number(viewport, "width"),
243
+ offsetLeft=_get_number(viewport, "offsetLeft"),
244
+ offsetTop=_get_number(viewport, "offsetTop"),
245
+ pageLeft=_get_number(viewport, "pageLeft"),
246
+ pageTop=_get_number(viewport, "pageTop"),
247
+ scale=_get_number(viewport, "scale"),
248
+ clientWidth=_get_number(viewport, "clientWidth"),
249
+ clientHeight=_get_number(viewport, "clientHeight"),
250
+ scrollWidth=_get_number(viewport, "scrollWidth"),
251
+ scrollHeight=_get_number(viewport, "scrollHeight"),
252
+ )
253
+
254
+
255
+ def add_set_of_mark(
256
+ screenshot: bytes | Image.Image | io.BufferedIOBase,
257
+ ROIs: Dict[str, InteractiveRegion],
258
+ ) -> Tuple[Image.Image, List[str], List[str], List[str]]:
259
+ if isinstance(screenshot, Image.Image):
260
+ return _add_set_of_mark(screenshot, ROIs)
261
+
262
+ if isinstance(screenshot, bytes):
263
+ screenshot = io.BytesIO(screenshot)
264
+
265
+ image = Image.open(cast(BinaryIO, screenshot))
266
+ comp, visible_rects, rects_above, rects_below = _add_set_of_mark(
267
+ image, ROIs
268
+ )
269
+ image.close()
270
+ return comp, visible_rects, rects_above, rects_below
271
+
272
+
273
+ def _add_set_of_mark(
274
+ screenshot: Image.Image, ROIs: Dict[str, InteractiveRegion]
275
+ ) -> Tuple[Image.Image, List[str], List[str], List[str]]:
276
+ visible_rects: List[str] = list()
277
+ rects_above: List[str] = list() # Scroll up to see
278
+ rects_below: List[str] = list() # Scroll down to see
279
+
280
+ fnt = ImageFont.load_default(14)
281
+ base = screenshot.convert("L").convert("RGBA")
282
+ overlay = Image.new("RGBA", base.size)
283
+
284
+ draw = ImageDraw.Draw(overlay)
285
+ for r in ROIs:
286
+ for rect in ROIs[r]["rects"]:
287
+ # Empty rectangles
288
+ if not rect:
289
+ continue
290
+ if rect["width"] * rect["height"] == 0:
291
+ continue
292
+
293
+ mid = (
294
+ (rect["right"] + rect["left"]) / 2.0,
295
+ (rect["top"] + rect["bottom"]) / 2.0,
296
+ )
297
+
298
+ if 0 <= mid[0] and mid[0] < base.size[0]:
299
+ if mid[1] < 0:
300
+ rects_above.append(r)
301
+ elif mid[1] >= base.size[1]:
302
+ rects_below.append(r)
303
+ else:
304
+ visible_rects.append(r)
305
+ _draw_roi(draw, int(r), fnt, rect)
306
+
307
+ comp = Image.alpha_composite(base, overlay)
308
+ overlay.close()
309
+ return comp, visible_rects, rects_above, rects_below
310
+
311
+
312
+ def _draw_roi(
313
+ draw: ImageDraw.ImageDraw,
314
+ idx: int,
315
+ font: ImageFont.FreeTypeFont | ImageFont.ImageFont,
316
+ rect: DOMRectangle,
317
+ ) -> None:
318
+ color = _color(idx)
319
+ luminance = color[0] * 0.3 + color[1] * 0.59 + color[2] * 0.11
320
+ text_color = (0, 0, 0, 255) if luminance > 90 else (255, 255, 255, 255)
321
+
322
+ roi = ((rect["left"], rect["top"]), (rect["right"], rect["bottom"]))
323
+
324
+ label_location = (rect["right"], rect["top"])
325
+ label_anchor = "rb"
326
+
327
+ if label_location[1] <= TOP_NO_LABEL_ZONE:
328
+ label_location = (rect["right"], rect["bottom"])
329
+ label_anchor = "rt"
330
+
331
+ draw.rectangle(
332
+ roi, outline=color, fill=(color[0], color[1], color[2], 48), width=2
333
+ )
334
+
335
+ bbox = draw.textbbox(
336
+ label_location,
337
+ str(idx),
338
+ font=font,
339
+ anchor=label_anchor,
340
+ align="center",
341
+ )
342
+ bbox = (bbox[0] - 3, bbox[1] - 3, bbox[2] + 3, bbox[3] + 3)
343
+ draw.rectangle(bbox, fill=color)
344
+
345
+ draw.text(
346
+ label_location,
347
+ str(idx),
348
+ fill=text_color,
349
+ font=font,
350
+ anchor=label_anchor,
351
+ align="center",
352
+ )
353
+
354
+
355
+ def _color(identifier: int) -> Tuple[int, int, int, int]:
356
+ rnd = random.Random(int(identifier))
357
+ color = [rnd.randint(0, 255), rnd.randint(125, 255), rnd.randint(0, 50)]
358
+ rnd.shuffle(color)
359
+ color.append(255)
360
+ return cast(Tuple[int, int, int, int], tuple(color))
361
+
362
+
363
+ class BaseBrowser:
364
+ def __init__(self, headless=True, cache_dir: Optional[str] = None):
365
+ r"""Initialize the WebBrowserToolkit instance.
366
+
367
+ Args:
368
+ headless (bool): Whether to run the browser in headless mode.
369
+ cache_dir (Union[str, None]): The directory to store cache files.
370
+
371
+ Returns:
372
+ None
373
+ """
374
+ from playwright.sync_api import (
375
+ sync_playwright,
376
+ )
377
+
378
+ self.history: list = []
379
+ self.headless = headless
380
+ self.playwright = sync_playwright().start()
381
+ self.page_history: list = [] # stores the history of visited pages
382
+
383
+ # set the cache directory
384
+ self.cache_dir = "tmp/"
385
+ os.makedirs(self.cache_dir, exist_ok=True)
386
+ if cache_dir is not None:
387
+ self.cache_dir = cache_dir
388
+
389
+ # load the page script
390
+ abs_dir_path = os.path.dirname(os.path.abspath(__file__))
391
+ page_script_path = os.path.join(abs_dir_path, "page_script.js")
392
+
393
+ try:
394
+ with open(page_script_path, "r", encoding='utf-8') as f:
395
+ self.page_script = f.read()
396
+ f.close()
397
+ except FileNotFoundError:
398
+ raise FileNotFoundError(
399
+ f"Page script file not found at path: {page_script_path}"
400
+ )
401
+
402
+ def init(self):
403
+ r"""Initialize the browser."""
404
+ self.browser = self.playwright.chromium.launch(
405
+ headless=self.headless
406
+ ) # Launch the browser, if headless is False, the browser will display
407
+ self.context = self.browser.new_context(
408
+ accept_downloads=True
409
+ ) # create a new context
410
+ self.page = self.context.new_page() # create a new page
411
+
412
+ def clean_cache(self):
413
+ r"""delete the cache directory and its contents."""
414
+ if os.path.exists(self.cache_dir):
415
+ shutil.rmtree(self.cache_dir)
416
+
417
+ def _wait_for_load(self, timeout: int = 20):
418
+ r"""Wait for a certain amount of time for the page to load."""
419
+ timeout_ms = timeout * 1000
420
+
421
+ self.page.wait_for_load_state("load", timeout=timeout_ms)
422
+ time.sleep(2)
423
+
424
+ def click_blank_area(self):
425
+ r"""Click a blank area of the page to unfocus the current element."""
426
+ self.page.mouse.click(0, 0)
427
+ self._wait_for_load()
428
+
429
+ def visit_page(self, url: str):
430
+ r"""Visit a page with the given URL."""
431
+
432
+ self.page.goto(url)
433
+ self._wait_for_load()
434
+ self.page_url = url
435
+
436
+ def ask_question_about_video(self, question: str) -> str:
437
+ r"""Ask a question about the video on the current page. It is suitable
438
+ to process youtube video.
439
+
440
+ Args:
441
+ question (str): The question to ask.
442
+
443
+ Returns:
444
+ str: The answer to the question.
445
+ """
446
+ video_analyzer = VideoAnalysisToolkit()
447
+ result = video_analyzer.ask_question_about_video(
448
+ self.page_url, question
449
+ )
450
+ return result
451
+
452
+ @retry_on_error()
453
+ def get_screenshot(
454
+ self, save_image: bool = False
455
+ ) -> Tuple[Image.Image, Union[str, None]]:
456
+ r"""Get a screenshot of the current page.
457
+
458
+ Args:
459
+ save_image (bool): Whether to save the image to the cache
460
+ directory.
461
+
462
+ Returns:
463
+ Tuple[Image.Image, str]: A tuple containing the screenshot image
464
+ and the path to the image file.
465
+ """
466
+
467
+ image_data = self.page.screenshot(timeout=60000)
468
+ image = Image.open(io.BytesIO(image_data))
469
+
470
+ file_path = None
471
+ if save_image:
472
+ # get url name to form a file name
473
+ url_name = self.page_url.split("/")[-1]
474
+ for char in ['\\', '/', ':', '*', '?', '"', '<', '>', '|', '.']:
475
+ url_name = url_name.replace(char, "_")
476
+
477
+ # get formatted time: mmddhhmmss
478
+ timestamp = datetime.datetime.now().strftime("%m%d%H%M%S")
479
+ file_path = os.path.join(
480
+ self.cache_dir, f"{url_name}_{timestamp}.png"
481
+ )
482
+ with open(file_path, "wb") as f:
483
+ image.save(f, "PNG")
484
+ f.close()
485
+
486
+ return image, file_path
487
+
488
+ def capture_full_page_screenshots(
489
+ self, scroll_ratio: float = 0.8
490
+ ) -> List[str]:
491
+ r"""Capture full page screenshots by scrolling the page with a buffer
492
+ zone.
493
+
494
+ Args:
495
+ scroll_ratio (float): The ratio of viewport height to scroll each
496
+ step (default: 0.7).
497
+
498
+ Returns:
499
+ List[str]: A list of paths to the screenshot files.
500
+ """
501
+ screenshots = []
502
+ scroll_height = self.page.evaluate("document.body.scrollHeight")
503
+ viewport_height = self.page.viewport_size["height"]
504
+ current_scroll = 0
505
+ screenshot_index = 1
506
+
507
+ url_name = self.page.url.split("/")[-1].replace(".", "_")
508
+ timestamp = datetime.datetime.now().strftime("%m%d%H%M%S")
509
+ base_file_path = os.path.join(
510
+ self.cache_dir, f"{url_name}_{timestamp}"
511
+ )
512
+
513
+ max_height = scroll_height - viewport_height
514
+ scroll_step = int(viewport_height * scroll_ratio)
515
+
516
+ last_height = 0
517
+
518
+ while True:
519
+ logger.debug(
520
+ f"Current scroll: {current_scroll}, max_height: "
521
+ f"{max_height}, step: {scroll_step}"
522
+ )
523
+
524
+ file_path = f"{base_file_path}_{screenshot_index}.png"
525
+ _, file_path = self.get_screenshot(save_image=True)
526
+ screenshots.append(file_path)
527
+
528
+ self.page.evaluate(f"window.scrollBy(0, {scroll_step})")
529
+ time.sleep(0.5)
530
+
531
+ current_scroll = self.page.evaluate("window.scrollY")
532
+ if abs(current_scroll - last_height) < viewport_height * 0.1:
533
+ break
534
+
535
+ last_height = current_scroll
536
+ screenshot_index += 1
537
+
538
+ return screenshots
539
+
540
+ def get_visual_viewport(self) -> VisualViewport:
541
+ r"""Get the visual viewport of the current page.
542
+
543
+ Returns:
544
+ VisualViewport: The visual viewport of the current page.
545
+ """
546
+ try:
547
+ self.page.evaluate(self.page_script)
548
+ except Exception as e:
549
+ logger.warning(f"Error evaluating page script: {e}")
550
+
551
+ return visualviewport_from_dict(
552
+ self.page.evaluate("MultimodalWebSurfer.getVisualViewport();")
553
+ )
554
+
555
+ def get_interactive_elements(self) -> List[Dict[str, Any]]:
556
+ # codes from magentic-one
557
+ try:
558
+ self.page.evaluate(self.page_script)
559
+ except Exception as e:
560
+ logger.warning(f"Error evaluating page script: {e}")
561
+
562
+ result = cast(
563
+ Dict[str, Dict[str, Any]],
564
+ self.page.evaluate("MultimodalWebSurfer.getInteractiveRects();"),
565
+ )
566
+
567
+ typed_results: Dict[str, InteractiveRegion] = {}
568
+ for k in result:
569
+ typed_results[k] = interactiveregion_from_dict(result[k])
570
+
571
+ return typed_results # type: ignore[return-value]
572
+
573
+ def get_som_screenshot(
574
+ self, save_image: bool = False
575
+ ) -> Tuple[Image.Image, Union[str, None]]:
576
+ r"""Get a screenshot of the current viewport with interactive elements
577
+ marked.
578
+
579
+ Args:
580
+ save_image (bool): Whether to save the image to the cache
581
+ directory.
582
+
583
+ Returns:
584
+ Tuple[Image.Image, str]: A tuple containing the screenshot image
585
+ and the path to the image file.
586
+ """
587
+
588
+ self._wait_for_load()
589
+ screenshot, _ = self.get_screenshot(save_image=False)
590
+ rects = self.get_interactive_elements()
591
+
592
+ file_path = None
593
+ comp, visible_rects, rects_above, rects_below = add_set_of_mark(
594
+ screenshot,
595
+ rects, # type: ignore[arg-type]
596
+ )
597
+ if save_image:
598
+ url_name = self.page_url.split("/")[-1]
599
+ for char in ['\\', '/', ':', '*', '?', '"', '<', '>', '|', '.']:
600
+ url_name = url_name.replace(char, "_")
601
+ timestamp = datetime.datetime.now().strftime("%m%d%H%M%S")
602
+ file_path = os.path.join(
603
+ self.cache_dir, f"{url_name}_{timestamp}.png"
604
+ )
605
+ with open(file_path, "wb") as f:
606
+ comp.save(f, "PNG")
607
+ f.close()
608
+
609
+ return comp, file_path
610
+
611
+ def scroll_up(self) -> None:
612
+ self.page.keyboard.press("PageUp")
613
+
614
+ def scroll_down(self) -> None:
615
+ self.page.keyboard.press("PageDown")
616
+
617
+ def get_url(self) -> str:
618
+ return self.page.url
619
+
620
+ def click_id(self, identifier: Union[str, int]):
621
+ if isinstance(identifier, int):
622
+ identifier = str(identifier)
623
+ target = self.page.locator(f"[__elementId='{identifier}']")
624
+
625
+ try:
626
+ target.wait_for(timeout=5000)
627
+ except (TimeoutError, Exception) as e:
628
+ logger.debug(f"Error during click operation: {e}")
629
+ raise ValueError("No such element.") from None
630
+
631
+ target.scroll_into_view_if_needed()
632
+
633
+ new_page = None
634
+ try:
635
+ with self.page.expect_event("popup", timeout=1000) as page_info:
636
+ box = cast(Dict[str, Union[int, float]], target.bounding_box())
637
+ self.page.mouse.click(
638
+ box["x"] + box["width"] / 2, box["y"] + box["height"] / 2
639
+ )
640
+ new_page = page_info.value
641
+
642
+ # If a new page is opened, switch to it
643
+ if new_page:
644
+ self.page_history.append(deepcopy(self.page.url))
645
+ self.page = new_page
646
+
647
+ except (TimeoutError, Exception) as e:
648
+ logger.debug(f"Error during click operation: {e}")
649
+ pass
650
+
651
+ self._wait_for_load()
652
+
653
+ def extract_url_content(self):
654
+ r"""Extract the content of the current page."""
655
+ content = self.page.content()
656
+ return content
657
+
658
+ def download_file_id(self, identifier: Union[str, int]) -> str:
659
+ r"""Download a file with the given selector.
660
+
661
+ Args:
662
+ identifier (str): The identifier of the file to download.
663
+ file_path (str): The path to save the downloaded file.
664
+
665
+ Returns:
666
+ str: The result of the action.
667
+ """
668
+
669
+ if isinstance(identifier, int):
670
+ identifier = str(identifier)
671
+ try:
672
+ target = self.page.locator(f"[__elementId='{identifier}']")
673
+ except (TimeoutError, Exception) as e:
674
+ logger.debug(f"Error during download operation: {e}")
675
+ logger.warning(
676
+ f"Element with identifier '{identifier}' not found."
677
+ )
678
+ return f"Element with identifier '{identifier}' not found."
679
+
680
+ target.scroll_into_view_if_needed()
681
+
682
+ file_path = os.path.join(self.cache_dir)
683
+ self._wait_for_load()
684
+
685
+ try:
686
+ with self.page.expect_download() as download_info:
687
+ target.click()
688
+ download = download_info.value
689
+ file_name = download.suggested_filename
690
+
691
+ file_path = os.path.join(file_path, file_name)
692
+ download.save_as(file_path)
693
+
694
+ return f"Downloaded file to path '{file_path}'."
695
+
696
+ except (TimeoutError, Exception) as e:
697
+ logger.debug(f"Error during download operation: {e}")
698
+ return f"Failed to download file with identifier '{identifier}'."
699
+
700
+ def fill_input_id(self, identifier: Union[str, int], text: str) -> str:
701
+ r"""Fill an input field with the given text, and then press Enter.
702
+
703
+ Args:
704
+ identifier (str): The identifier of the input field.
705
+ text (str): The text to fill.
706
+
707
+ Returns:
708
+ str: The result of the action.
709
+ """
710
+ if isinstance(identifier, int):
711
+ identifier = str(identifier)
712
+
713
+ try:
714
+ target = self.page.locator(f"[__elementId='{identifier}']")
715
+ except (TimeoutError, Exception) as e:
716
+ logger.debug(f"Error during fill operation: {e}")
717
+ logger.warning(
718
+ f"Element with identifier '{identifier}' not found."
719
+ )
720
+ return f"Element with identifier '{identifier}' not found."
721
+
722
+ target.scroll_into_view_if_needed()
723
+ target.focus()
724
+ try:
725
+ target.fill(text)
726
+ except (TimeoutError, Exception) as e:
727
+ logger.debug(f"Error during fill operation: {e}")
728
+ target.press_sequentially(text)
729
+
730
+ target.press("Enter")
731
+ self._wait_for_load()
732
+ return (
733
+ f"Filled input field '{identifier}' with text '{text}' "
734
+ f"and pressed Enter."
735
+ )
736
+
737
+ def scroll_to_bottom(self) -> str:
738
+ self.page.evaluate("window.scrollTo(0, document.body.scrollHeight);")
739
+ self._wait_for_load()
740
+ return "Scrolled to the bottom of the page."
741
+
742
+ def scroll_to_top(self) -> str:
743
+ self.page.evaluate("window.scrollTo(0, 0);")
744
+ self._wait_for_load()
745
+ return "Scrolled to the top of the page."
746
+
747
+ def hover_id(self, identifier: Union[str, int]) -> str:
748
+ r"""Hover over an element with the given identifier.
749
+
750
+ Args:
751
+ identifier (str): The identifier of the element to hover over.
752
+
753
+ Returns:
754
+ str: The result of the action.
755
+ """
756
+ if isinstance(identifier, int):
757
+ identifier = str(identifier)
758
+ try:
759
+ target = self.page.locator(f"[__elementId='{identifier}']")
760
+ except (TimeoutError, Exception) as e:
761
+ logger.debug(f"Error during hover operation: {e}")
762
+ logger.warning(
763
+ f"Element with identifier '{identifier}' not found."
764
+ )
765
+ return f"Element with identifier '{identifier}' not found."
766
+
767
+ target.scroll_into_view_if_needed()
768
+ target.hover()
769
+ self._wait_for_load()
770
+ return f"Hovered over element with identifier '{identifier}'."
771
+
772
+ def find_text_on_page(self, search_text: str) -> str:
773
+ r"""Find the next given text on the page, and scroll the page to the
774
+ targeted text. It is equivalent to pressing Ctrl + F and searching for
775
+ the text.
776
+ """
777
+ # ruff: noqa: E501
778
+ script = f"""
779
+ (function() {{
780
+ let text = "{search_text}";
781
+ let found = window.find(text);
782
+ if (!found) {{
783
+ let elements = document.querySelectorAll("*:not(script):not(style)");
784
+ for (let el of elements) {{
785
+ if (el.innerText && el.innerText.includes(text)) {{
786
+ el.scrollIntoView({{behavior: "smooth", block: "center"}});
787
+ el.style.backgroundColor = "yellow";
788
+ el.style.border = '2px solid red';
789
+ return true;
790
+ }}
791
+ }}
792
+ return false;
793
+ }}
794
+ return true;
795
+ }})();
796
+ """
797
+ found = self.page.evaluate(script)
798
+ self._wait_for_load()
799
+ if found:
800
+ return f"Found text '{search_text}' on the page."
801
+ else:
802
+ return f"Text '{search_text}' not found on the page."
803
+
804
+ def back(self):
805
+ r"""Navigate back to the previous page."""
806
+
807
+ page_url_before = self.page.url
808
+ self.page.go_back()
809
+
810
+ page_url_after = self.page.url
811
+
812
+ if page_url_after == "about:blank":
813
+ self.visit_page(page_url_before)
814
+
815
+ if page_url_before == page_url_after:
816
+ # If the page is not changed, try to use the history
817
+ if len(self.page_history) > 0:
818
+ self.visit_page(self.page_history.pop())
819
+
820
+ time.sleep(1)
821
+ self._wait_for_load()
822
+
823
+ def close(self):
824
+ self.browser.close()
825
+ self.playwright.stop()
826
+
827
+ # ruff: noqa: E501
828
+ def show_interactive_elements(self):
829
+ r"""Show simple interactive elements on the current page."""
830
+ self.page.evaluate(self.page_script)
831
+ self.page.evaluate("""
832
+ () => {
833
+ document.querySelectorAll('a, button, input, select, textarea, [tabindex]:not([tabindex="-1"]), [contenteditable="true"]').forEach(el => {
834
+ el.style.border = '2px solid red';
835
+ });
836
+ }
837
+ """)
838
+
839
+ @retry_on_error()
840
+ def get_webpage_content(self) -> str:
841
+ from html2text import html2text
842
+
843
+ self._wait_for_load()
844
+ html_content = self.page.content()
845
+
846
+ markdown_content = html2text(html_content)
847
+ return markdown_content
848
+
849
+
850
+ class WebToolkit(BaseToolkit):
851
+ r"""A class for browsing the web and interacting with web pages.
852
+
853
+ This class provides methods for browsing the web and interacting with web
854
+ pages.
855
+ """
856
+
857
+ def __init__(
858
+ self,
859
+ headless: bool = False,
860
+ cache_dir: Optional[str] = None,
861
+ history_window: int = 5,
862
+ web_agent_model: Optional[BaseModelBackend] = None,
863
+ planning_agent_model: Optional[BaseModelBackend] = None,
864
+ output_language: str = "en",
865
+ ):
866
+ r"""Initialize the WebToolkit instance.
867
+
868
+ Args:
869
+ headless (bool): Whether to run the browser in headless mode.
870
+ cache_dir (Union[str, None]): The directory to store cache files.
871
+ history_window (int): The window size for storing the history of
872
+ actions.
873
+ web_agent_model (Optional[BaseModelBackend]): The model backend
874
+ for the web agent.
875
+ planning_agent_model (Optional[BaseModelBackend]): The model
876
+ backend for the planning agent.
877
+ """
878
+
879
+ self.browser = BaseBrowser(headless=headless, cache_dir=cache_dir)
880
+
881
+ self.history_window = history_window
882
+ self.web_agent_model = web_agent_model
883
+ self.planning_agent_model = planning_agent_model
884
+ self.output_language = output_language
885
+
886
+ self.history: list = []
887
+ self.web_agent, self.planning_agent = self._initialize_agent()
888
+
889
+ def _reset(self):
890
+ self.web_agent.reset()
891
+ self.planning_agent.reset()
892
+ self.history = []
893
+ os.makedirs(self.browser.cache_dir, exist_ok=True)
894
+
895
+ def _initialize_agent(self) -> Tuple["ChatAgent", "ChatAgent"]:
896
+ r"""Initialize the agent."""
897
+ from camel.agents import ChatAgent
898
+
899
+ if self.web_agent_model is None:
900
+ web_agent_model = ModelFactory.create(
901
+ model_platform=ModelPlatformType.OPENAI,
902
+ model_type=ModelType.GPT_4O,
903
+ model_config_dict={"temperature": 0, "top_p": 1},
904
+ )
905
+ else:
906
+ web_agent_model = self.web_agent_model
907
+
908
+ if self.planning_agent_model is None:
909
+ planning_model = ModelFactory.create(
910
+ model_platform=ModelPlatformType.OPENAI,
911
+ model_type=ModelType.O3_MINI,
912
+ )
913
+ else:
914
+ planning_model = self.planning_agent_model
915
+
916
+ system_prompt = """
917
+ You are a helpful web agent that can assist users in browsing the web.
918
+ Given a high-level task, you can leverage predefined browser tools to help
919
+ users achieve their goals.
920
+ """
921
+
922
+ web_agent = ChatAgent(
923
+ system_message=system_prompt,
924
+ model=web_agent_model,
925
+ output_language=self.output_language,
926
+ )
927
+
928
+ planning_system_prompt = """
929
+ You are a helpful planning agent that can assist users in planning complex
930
+ tasks which need multi-step browser interaction.
931
+ """
932
+
933
+ planning_agent = ChatAgent(
934
+ system_message=planning_system_prompt,
935
+ model=planning_model,
936
+ output_language=self.output_language,
937
+ )
938
+
939
+ return web_agent, planning_agent
940
+
941
+ def _observe(
942
+ self, task_prompt: str, detailed_plan: Optional[str] = None
943
+ ) -> Tuple[str, str, str]:
944
+ r"""Let agent observe the current environment, and get the next action."""
945
+
946
+ detailed_plan_prompt = ""
947
+
948
+ if detailed_plan is not None:
949
+ detailed_plan_prompt = f"""
950
+ Here is a plan about how to solve the task step-by-step which you must follow:
951
+ <detailed_plan>{detailed_plan}<detailed_plan>
952
+ """
953
+
954
+ observe_prompt = f"""
955
+ Please act as a web agent to help me complete the following high-level task:
956
+ <task>{task_prompt}</task>
957
+ Now, I have made screenshot (only the current viewport, not the full webpage)
958
+ based on the current browser state, and marked interactive elements in the
959
+ webpage.
960
+ Please carefully examine the requirements of the task, and current state of
961
+ the browser, and provide the next appropriate action to take.
962
+
963
+ {detailed_plan_prompt}
964
+
965
+ Here are the current available browser functions you can use:
966
+ {AVAILABLE_ACTIONS_PROMPT}
967
+
968
+ Here are the latest {self.history_window} trajectory (at most) you have taken:
969
+ <history>
970
+ {self.history[-self.history_window:]}
971
+ </history>
972
+
973
+ Your output should be in json format, including the following fields:
974
+ - `observation`: The detailed image description about the current viewport. Do
975
+ not over-confident about the correctness of the history actions. You should
976
+ always check the current viewport to make sure the correctness of the next
977
+ action.
978
+ - `reasoning`: The reasoning about the next action you want to take, and the
979
+ possible obstacles you may encounter, and how to solve them. Do not forget to
980
+ check the history actions to avoid the same mistakes.
981
+ - `action_code`: The action code you want to take. It is only one step action
982
+ code, without any other texts (such as annotation)
983
+
984
+ Here are an example of the output:
985
+ ```json
986
+ {{
987
+ "observation": [IMAGE_DESCRIPTION],
988
+ "reasoning": [YOUR_REASONING],
989
+ "action_code": `fill_input_id([ID], [TEXT])`
990
+ }}
991
+
992
+ Here are some tips for you:
993
+ - Never forget the overall question: **{task_prompt}**
994
+ - Maybe after a certain operation (e.g. click_id), the page content has not
995
+ changed. You can check whether the action step is successful by looking at the
996
+ `success` of the action step in the history. If successful, it means that the
997
+ page content is indeed the same after the click. You need to try other methods.
998
+ - If using one way to solve the problem is not successful, try other ways.
999
+ Make sure your provided ID is correct!
1000
+ - Some cases are very complex and need to be achieve by an iterative process.
1001
+ You can use the `back()` function to go back to the previous page to try other
1002
+ methods.
1003
+ - There are many links on the page, which may be useful for solving the
1004
+ problem. You can use the `click_id()` function to click on the link to see if
1005
+ it is useful.
1006
+ - Always keep in mind that your action must be based on the ID shown in the
1007
+ current image or viewport, not the ID shown in the history.
1008
+ - Do not use `stop()` lightly. Always remind yourself that the image only
1009
+ shows a part of the full page. If you cannot find the answer, try to use
1010
+ functions like `scroll_up()` and `scroll_down()` to check the full content of
1011
+ the webpage before doing anything else, because the answer or next key step
1012
+ may be hidden in the content below.
1013
+ - If the webpage needs human verification, you must avoid processing it.
1014
+ Please use `back()` to go back to the previous page, and try other ways.
1015
+ - If you have tried everything and still cannot resolve the issue, please stop
1016
+ the simulation, and report issues you have encountered.
1017
+ - Check the history actions carefully, detect whether you have repeatedly made
1018
+ the same actions or not.
1019
+ - When dealing with wikipedia revision history related tasks, you need to
1020
+ think about the solution flexibly. First, adjust the browsing history
1021
+ displayed on a single page to the maximum, and then make use of the
1022
+ find_text_on_page function. This is extremely useful which can quickly locate
1023
+ the text you want to find and skip massive amount of useless information.
1024
+ - Flexibly use interactive elements like slide down selection bar to filter
1025
+ out the information you need. Sometimes they are extremely useful.
1026
+ ```
1027
+ """
1028
+
1029
+ # get current state
1030
+ som_screenshot, som_screenshot_path = self.browser.get_som_screenshot(
1031
+ save_image=True
1032
+ )
1033
+ img = _reload_image(som_screenshot)
1034
+ message = BaseMessage.make_user_message(
1035
+ role_name='user', content=observe_prompt, image_list=[img]
1036
+ )
1037
+ resp = self.web_agent.step(message)
1038
+
1039
+ resp_content = resp.msgs[0].content
1040
+
1041
+ resp_dict = _parse_json_output(resp_content)
1042
+ observation_result: str = resp_dict.get("observation", "")
1043
+ reasoning_result: str = resp_dict.get("reasoning", "")
1044
+ action_code: str = resp_dict.get("action_code", "")
1045
+
1046
+ if action_code and "(" in action_code and ")" not in action_code:
1047
+ action_match = re.search(
1048
+ r'"action_code"\s*:\s*[`"]([^`"]*\([^)]*\))[`"]', resp_content
1049
+ )
1050
+ if action_match:
1051
+ action_code = action_match.group(1)
1052
+ else:
1053
+ logger.warning(
1054
+ f"Incomplete action_code detected: {action_code}"
1055
+ )
1056
+ if action_code.startswith("fill_input_id("):
1057
+ parts = action_code.split(",", 1)
1058
+ if len(parts) > 1:
1059
+ id_part = (
1060
+ parts[0].replace("fill_input_id(", "").strip()
1061
+ )
1062
+ action_code = f"fill_input_id({id_part}, 'Please fill the text here.')"
1063
+
1064
+ action_code = action_code.replace("`", "").strip()
1065
+
1066
+ return observation_result, reasoning_result, action_code
1067
+
1068
+ def _act(self, action_code: str) -> Tuple[bool, str]:
1069
+ r"""Let agent act based on the given action code.
1070
+ Args:
1071
+ action_code (str): The action code to act.
1072
+
1073
+ Returns:
1074
+ Tuple[bool, str]: A tuple containing a boolean indicating whether
1075
+ the action was successful, and the information to be returned.
1076
+ """
1077
+
1078
+ def _check_if_with_feedback(action_code: str) -> bool:
1079
+ r"""Check if the action code needs feedback."""
1080
+
1081
+ for action_with_feedback in ACTION_WITH_FEEDBACK_LIST:
1082
+ if action_with_feedback in action_code:
1083
+ return True
1084
+
1085
+ return False
1086
+
1087
+ prefix = "self.browser."
1088
+ code = f"{prefix}{action_code}"
1089
+
1090
+ try:
1091
+ if _check_if_with_feedback(action_code):
1092
+ # execute code, and get the executed result
1093
+ result = eval(code)
1094
+ time.sleep(1)
1095
+ return True, result
1096
+
1097
+ else:
1098
+ exec(code)
1099
+ time.sleep(1)
1100
+ return True, "Action was successful."
1101
+
1102
+ except Exception as e:
1103
+ time.sleep(1)
1104
+ return (
1105
+ False,
1106
+ f"Error while executing the action {action_code}: {e}. "
1107
+ f"If timeout, please recheck whether you have provided the "
1108
+ f"correct identifier.",
1109
+ )
1110
+
1111
+ def _get_final_answer(self, task_prompt: str) -> str:
1112
+ r"""Get the final answer based on the task prompt and current browser state.
1113
+ It is used when the agent thinks that the task can be completed without any further action, and answer can be directly found in the current viewport.
1114
+ """
1115
+
1116
+ prompt = f"""
1117
+ 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.
1118
+ Here are all trajectory we have taken:
1119
+ <history>{self.history}</history>
1120
+ 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>
1121
+ """
1122
+
1123
+ message = BaseMessage.make_user_message(
1124
+ role_name='user',
1125
+ content=prompt,
1126
+ )
1127
+
1128
+ resp = self.web_agent.step(message)
1129
+ return resp.msgs[0].content
1130
+
1131
+ def _make_reflection(self, task_prompt: str) -> str:
1132
+ r"""Make a reflection about the current state and the task prompt."""
1133
+
1134
+ reflection_prompt = f"""
1135
+ Now we are working on a complex task that requires multi-step browser interaction. The task is: <task>{task_prompt}</task>
1136
+ To achieve this goal, we have made a series of observations, reasonings, and actions. We have also made a reflection on previous states.
1137
+
1138
+ Here are the global available browser functions we can use:
1139
+ {AVAILABLE_ACTIONS_PROMPT}
1140
+
1141
+ Here are the latest {self.history_window} trajectory (at most) we have taken:
1142
+ <history>{self.history[-self.history_window:]}</history>
1143
+
1144
+ The image provided is the current state of the browser, where we have marked interactive elements.
1145
+ Please carefully examine the requirements of the task, and the current state of the browser, and then make reflections on the previous steps, thinking about whether they are helpful or not, and why, offering detailed feedback and suggestions for the next steps.
1146
+ Your output should be in json format, including the following fields:
1147
+ - `reflection`: The reflection about the previous steps, thinking about whether they are helpful or not, and why, offering detailed feedback.
1148
+ - `suggestion`: The suggestion for the next steps, offering detailed suggestions, including the common solutions to the overall task based on the current state of the browser.
1149
+ """
1150
+ som_image, _ = self.browser.get_som_screenshot()
1151
+ img = _reload_image(som_image)
1152
+
1153
+ message = BaseMessage.make_user_message(
1154
+ role_name='user', content=reflection_prompt, image_list=[img]
1155
+ )
1156
+
1157
+ resp = self.web_agent.step(message)
1158
+
1159
+ return resp.msgs[0].content
1160
+
1161
+ def _task_planning(self, task_prompt: str, start_url: str) -> str:
1162
+ r"""Plan the task based on the given task prompt."""
1163
+
1164
+ # Here are the available browser functions we can use: {AVAILABLE_ACTIONS_PROMPT}
1165
+
1166
+ planning_prompt = f"""
1167
+ <task>{task_prompt}</task>
1168
+ According to the problem above, if we use browser interaction, what is the general process of the interaction after visiting the webpage `{start_url}`?
1169
+
1170
+ Please note that it can be viewed as Partially Observable MDP. Do not over-confident about your plan.
1171
+ Please first restate the task in detail, and then provide a detailed plan to solve the task.
1172
+ """
1173
+ # Here are some tips for you: Please note that we can only see a part of the full page because of the limited viewport after an action. Thus, do not forget to use methods like `scroll_up()` and `scroll_down()` to check the full content of the webpage, because the answer or next key step may be hidden in the content below.
1174
+
1175
+ message = BaseMessage.make_user_message(
1176
+ role_name='user', content=planning_prompt
1177
+ )
1178
+
1179
+ resp = self.planning_agent.step(message)
1180
+ return resp.msgs[0].content
1181
+
1182
+ def _task_replanning(
1183
+ self, task_prompt: str, detailed_plan: str
1184
+ ) -> Tuple[bool, str]:
1185
+ r"""Replan the task based on the given task prompt.
1186
+
1187
+ Args:
1188
+ task_prompt (str): The original task prompt.
1189
+ detailed_plan (str): The detailed plan to replan.
1190
+
1191
+ Returns:
1192
+ Tuple[bool, str]: A tuple containing a boolean indicating whether the task needs to be replanned, and the replanned schema.
1193
+ """
1194
+
1195
+ # Here are the available browser functions we can use: {AVAILABLE_ACTIONS_PROMPT}
1196
+ replanning_prompt = f"""
1197
+ We are using browser interaction to solve a complex task which needs multi-step actions.
1198
+ Here are the overall task:
1199
+ <overall_task>{task_prompt}</overall_task>
1200
+
1201
+ In order to solve the task, we made a detailed plan previously. Here is the detailed plan:
1202
+ <detailed plan>{detailed_plan}</detailed plan>
1203
+
1204
+ 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:
1205
+ <history>{self.history[-self.history_window:]}</history>
1206
+
1207
+ 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.
1208
+ 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).
1209
+
1210
+ Your output should be in json format, including the following fields:
1211
+ - `if_need_replan`: bool, A boolean value indicating whether the task needs to be fundamentally replanned.
1212
+ - `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.
1213
+ """
1214
+ resp = self.planning_agent.step(replanning_prompt)
1215
+ resp_dict = _parse_json_output(resp.msgs[0].content)
1216
+
1217
+ if_need_replan = resp_dict.get("if_need_replan", False)
1218
+ replanned_schema = resp_dict.get("replanned_schema", "")
1219
+
1220
+ if if_need_replan:
1221
+ return True, replanned_schema
1222
+ else:
1223
+ return False, replanned_schema
1224
+
1225
+ @dependencies_required("playwright")
1226
+ def browser_simulation(
1227
+ self, task_prompt: str, start_url: str, round_limit: int = 12
1228
+ ) -> str:
1229
+ r"""A powerful toolkit which can simulate the browser interaction to solve the task which needs multi-step actions.
1230
+
1231
+ Args:
1232
+ task_prompt (str): The task prompt to solve.
1233
+ start_url (str): The start URL to visit.
1234
+ round_limit (int): The round limit to solve the task (default: 12).
1235
+
1236
+ Returns:
1237
+ str: The simulation result to the task.
1238
+ """
1239
+
1240
+ self._reset()
1241
+ task_completed = False
1242
+ detailed_plan = self._task_planning(task_prompt, start_url)
1243
+ logger.debug(f"Detailed plan: {detailed_plan}")
1244
+
1245
+ self.browser.init()
1246
+ self.browser.visit_page(start_url)
1247
+
1248
+ for i in range(round_limit):
1249
+ observation, reasoning, action_code = self._observe(
1250
+ task_prompt, detailed_plan
1251
+ )
1252
+ logger.debug(f"Observation: {observation}")
1253
+ logger.debug(f"Reasoning: {reasoning}")
1254
+ logger.debug(f"Action code: {action_code}")
1255
+
1256
+ if "stop" in action_code:
1257
+ task_completed = True
1258
+ trajectory_info = {
1259
+ "round": i,
1260
+ "observation": observation,
1261
+ "thought": reasoning,
1262
+ "action": action_code,
1263
+ "action_if_success": True,
1264
+ "info": None,
1265
+ "current_url": self.browser.get_url(),
1266
+ }
1267
+ self.history.append(trajectory_info)
1268
+ break
1269
+
1270
+ else:
1271
+ success, info = self._act(action_code)
1272
+ if not success:
1273
+ logger.warning(f"Error while executing the action: {info}")
1274
+
1275
+ trajectory_info = {
1276
+ "round": i,
1277
+ "observation": observation,
1278
+ "thought": reasoning,
1279
+ "action": action_code,
1280
+ "action_if_success": success,
1281
+ "info": info,
1282
+ "current_url": self.browser.get_url(),
1283
+ }
1284
+ self.history.append(trajectory_info)
1285
+
1286
+ # replan the task if necessary
1287
+ if_need_replan, replanned_schema = self._task_replanning(
1288
+ task_prompt, detailed_plan
1289
+ )
1290
+ if if_need_replan:
1291
+ detailed_plan = replanned_schema
1292
+ logger.debug(f"Replanned schema: {replanned_schema}")
1293
+
1294
+ if not task_completed:
1295
+ simulation_result = f"""
1296
+ The task is not completed within the round limit. Please check the last round {self.history_window} information to see if there is any useful information:
1297
+ <history>{self.history[-self.history_window:]}</history>
1298
+ """
1299
+
1300
+ else:
1301
+ simulation_result = self._get_final_answer(task_prompt)
1302
+
1303
+ self.browser.close()
1304
+ return simulation_result
1305
+
1306
+ def get_tools(self) -> List[FunctionTool]:
1307
+ return [FunctionTool(self.browser_simulation)]