Spaces:
Sleeping
Sleeping
File size: 37,840 Bytes
ea7486e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 |
# coding: utf-8
# Copyright (c) 2025 inclusionAI.
import os
import traceback
import asyncio
import time
from typing import Tuple, Any
from examples.tools.tool_action import BrowserAction
from aworld.core.tool.action_factory import ActionFactory
from aworld.core.common import ActionModel, ActionResult, Observation
from examples.tools.browsers.util.dom import DOMElementNode
from aworld.logs.util import logger
from examples.tools.browsers.action.utils import DomUtil
from aworld.core.tool.action import ExecutableAction
from aworld.utils import import_packages
from aworld.models.llm import get_llm_model, call_llm_model
def get_page(**kwargs):
tool = kwargs.get("tool")
if tool is None:
page = kwargs.get('page')
else:
page = tool.page
return page
def get_browser(**kwargs):
tool = kwargs.get("tool")
if tool is None:
page = kwargs.get('browser')
else:
page = tool.context
return page
@ActionFactory.register(name=BrowserAction.GO_TO_URL.value.name,
desc=BrowserAction.GO_TO_URL.value.desc,
tool_name="browser")
class GotoUrl(ExecutableAction):
def act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
logger.info(f"exec {BrowserAction.GO_TO_URL.value.name} action")
page = get_page(**kwargs)
if page is None:
logger.warning(f"{BrowserAction.GO_TO_URL.name} page is none")
return ActionResult(content="no page", keep=True), page
params = action.params
url = params.get("url")
if not url:
logger.warning("empty url, go to nothing.")
return ActionResult(content="empty url", keep=True), page
items = url.split('://')
if len(items) == 1:
if items[0][0] != '/':
url = "file://" + os.path.join(os.getcwd(), url)
page.goto(url)
page.wait_for_load_state()
msg = f'Navigated to {url}'
logger.info(msg)
return ActionResult(content=msg, keep=True), page
async def async_act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
logger.info(f"exec {BrowserAction.GO_TO_URL.value.name} action")
page = get_page(**kwargs)
if page is None:
logger.warning(f"{BrowserAction.GO_TO_URL.name} page is none")
return ActionResult(content="no page", keep=True), page
url = action.params.get("url")
if not url:
logger.warning("empty url, go to nothing.")
return ActionResult(content="empty url", keep=True), page
items = url.split('://')
if len(items) == 1:
if items[0][0] != '/':
url = "file://" + os.path.join(os.getcwd(), url)
await page.goto(url)
await page.wait_for_load_state()
msg = f'Navigated to {url}'
logger.info(msg)
return ActionResult(content=msg, keep=True), page
@ActionFactory.register(name=BrowserAction.INPUT_TEXT.value.name,
desc=BrowserAction.INPUT_TEXT.value.desc,
tool_name="browser")
class InputText(ExecutableAction):
def act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
logger.info(f"exec {BrowserAction.INPUT_TEXT.value.name} action")
page = get_page(**kwargs)
if page is None:
logger.warning(f"{BrowserAction.INPUT_TEXT.name} page is none")
return ActionResult(content="input text no page", keep=True), page
params = action.params
index = params.get("index", 0)
# compatible with int and str datatype
index = int(index)
input = params.get("text", "")
ob: Observation = kwargs.get("observation")
if not ob or index not in ob.dom_tree.element_map:
raise RuntimeError(f'Element index {index} does not exist')
if not input:
raise ValueError(f'No input to the page')
element_node = ob.dom_tree.element_map[index]
self.input_to_element(input, page, element_node)
msg = f'Input {input} into index {index}'
logger.info(f"action {msg}")
logger.debug(f'Element xpath: {element_node.xpath}')
return ActionResult(content=msg, keep=True), page
async def async_act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
logger.info(f"exec {BrowserAction.INPUT_TEXT.value.name} action")
page = get_page(**kwargs)
if page is None:
logger.warning(f"{BrowserAction.INPUT_TEXT.name} page is none")
return ActionResult(content="input text no page", keep=True), page
params = action.params
index = params.get("index")
# compatible with int and str datatype
index = int(index)
input = params.get("text", "")
ob: Observation = kwargs.get("observation")
if not ob or index not in ob.dom_tree.element_map:
raise RuntimeError(f'Element index {index} does not exist')
if not input:
raise ValueError(f'No input to the page')
element_node = ob.dom_tree.element_map[index]
await self.async_input_to_element(input, page, element_node)
msg = f'Input {input} into index {index}'
logger.info(f"action {msg}")
logger.debug(f'Element xpath: {element_node.xpath}')
return ActionResult(content=msg, keep=True), page
def input_to_element(self, input: str, page, element_node: DOMElementNode):
try:
# Highlight before typing
# if element_node.highlight_index is not None:
# await self._update_state(focus_element=element_node.highlight_index)
element_handle = DomUtil.get_locate_element(page, element_node)
if element_handle is None:
raise RuntimeError(f'Element: {repr(element_node)} not found')
# Ensure element is ready for input
try:
element_handle.wait_for_element_state('stable', timeout=1000)
element_handle.scroll_into_view_if_needed(timeout=1000)
except Exception:
pass
# Get element properties to determine input method
is_contenteditable = element_handle.get_property('isContentEditable')
# Different handling for contenteditable vs input fields
if is_contenteditable.json_value():
element_handle.evaluate('el => el.textContent = ""')
element_handle.type(input, delay=5)
else:
element_handle.fill(input)
except Exception as e:
logger.warning(f'Failed to input text into element: {repr(element_node)}. Error: {str(e)}')
raise RuntimeError(f'Failed to input text into index {element_node.highlight_index}')
async def async_input_to_element(self, input: str, page, element_node: DOMElementNode):
try:
element_handle = await DomUtil.async_get_locate_element(page, element_node)
if element_handle is None:
raise RuntimeError(f'Element: {repr(element_node)} not found')
# Ensure element is ready for input
try:
await element_handle.wait_for_element_state('stable', timeout=1000)
await element_handle.scroll_into_view_if_needed(timeout=1000)
except Exception:
pass
# Get element properties to determine input method
is_contenteditable = await element_handle.get_property('isContentEditable')
# Different handling for contenteditable vs input fields
if await is_contenteditable.json_value():
await element_handle.evaluate('el => el.textContent = ""')
await element_handle.type(input, delay=5)
else:
await element_handle.fill(input)
except Exception as e:
logger.warning(f'Failed to input text into element: {repr(element_node)}. Error: {str(e)}')
raise RuntimeError(f'Failed to input text into index {element_node.highlight_index}')
@ActionFactory.register(name=BrowserAction.CLICK_ELEMENT.value.name,
desc=BrowserAction.CLICK_ELEMENT.value.desc,
tool_name="browser")
class ClickElement(ExecutableAction):
def __init__(self):
import_packages(['playwright', 'markdownify'])
def act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
from playwright.sync_api import BrowserContext
logger.info(f"exec {BrowserAction.CLICK_ELEMENT.value.name} action")
page = get_page(**kwargs)
if page is None:
logger.warning(f"{BrowserAction.CLICK_ELEMENT.name} page is none")
return ActionResult(content="input text no page", keep=True), page
browser: BrowserContext = get_browser(**kwargs)
if browser is None:
logger.warning(f"{BrowserAction.CLICK_ELEMENT.name} browser context is none")
return ActionResult(content="none browser context", keep=True), page
index = action.params.get("index")
# compatible with int and str datatype
index = int(index)
ob: Observation = kwargs.get("observation")
if not ob or index not in ob.dom_tree.element_map:
raise RuntimeError(f'Element index {index} does not exist')
if not input:
raise ValueError(f'No input to the page')
element_node = ob.dom_tree.element_map[index]
try:
pages = len(browser.pages)
msg = f'Clicked button with index {index}: {element_node.get_all_text_till_next_clickable_element(max_depth=2)}'
logger.info(msg)
DomUtil.click_element(page, element_node, browser=browser)
logger.debug(f'Element xpath: {element_node.xpath}')
if len(browser.pages) > pages:
new_tab_msg = 'Open the new tab'
msg += f' - {new_tab_msg}'
logger.info(new_tab_msg)
page = browser.pages[-1]
page.bring_to_front()
page.wait_for_load_state(timeout=60000)
return ActionResult(content=msg, keep=True), page
except Exception as e:
logger.warning(f'Element not clickable with index {index} - most likely the page changed')
return ActionResult(error=str(e)), page
async def async_act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
logger.info(f"exec {BrowserAction.CLICK_ELEMENT.value.name} action")
page = get_page(**kwargs)
if page is None:
logger.warn(f"{BrowserAction.CLICK_ELEMENT.name} page is none")
return ActionResult(content="input text no page", keep=True), page
browser = get_browser(**kwargs)
if browser is None:
logger.warning(f"{BrowserAction.CLICK_ELEMENT.name} browser context is none")
return ActionResult(content="none browser context", keep=True), page
index = action.params.get("index")
# compatible with int and str datatype
index = int(index)
ob: Observation = kwargs.get("observation")
if not ob or index not in ob.dom_tree.element_map:
raise RuntimeError(f'Element index {index} does not exist')
if not input:
raise ValueError(f'No input to the page')
element_node = ob.dom_tree.element_map[index]
pages = len(browser.pages)
try:
await DomUtil.async_click_element(page, element_node, browser=browser)
msg = f'Clicked button with index {index}: {element_node.get_all_text_till_next_clickable_element(max_depth=2)}'
logger.info(msg)
logger.debug(f'Element xpath: {element_node.xpath}')
if len(browser.pages) > pages:
new_tab_msg = 'Open the new tab'
msg += f' - {new_tab_msg}'
logger.info(new_tab_msg)
page = browser.pages[-1]
await page.bring_to_front()
await page.wait_for_load_state(timeout=60000)
return ActionResult(content=msg, keep=True), page
except Exception as e:
logger.warning(f'Element not clickable with index {index} - most likely the page changed')
return ActionResult(error=str(e)), page
# SEARCH_ENGINE = {"": "https://www.google.com/search?udm=14&q=",
# "google": "https://www.google.com/search?udm=14&q="}
SEARCH_ENGINE = {"": "https://www.bing.com/search?q=",
"google": "https://www.bing.com/search?q="}
@ActionFactory.register(name=BrowserAction.SEARCH.value.name,
desc=BrowserAction.SEARCH.value.desc,
tool_name="browser")
class Search(ExecutableAction):
def act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
logger.info(f"exec {BrowserAction.SEARCH.value.name} action")
page = get_page(**kwargs)
if page is None:
logger.warning(f"{BrowserAction.SEARCH.name} page is none")
return ActionResult(content="search no page", keep=True), page
params = action.params if action.params else {}
engine = params.get("engine", "")
url = SEARCH_ENGINE.get(engine)
query = params.get("query")
page.goto(f'{url}{query}')
page.wait_for_load_state()
msg = f'Searched for "{query}" in {url}'
logger.info(msg)
return ActionResult(content=msg, keep=True), page
async def async_act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
logger.info(f"exec {BrowserAction.SEARCH.value.name} action")
page = get_page(**kwargs)
if page is None:
logger.warning(f"{BrowserAction.SEARCH.name} page is none")
return ActionResult(content="search no page", keep=True), page
params = action.params if action.params else {}
engine = params.get("engine", "")
url = SEARCH_ENGINE.get(engine)
query = params.get("query")
await page.goto(f'{url}{query}')
await page.wait_for_load_state()
msg = f'Searched for "{query}" in {url}'
logger.info(msg)
return ActionResult(content=msg, keep=True), page
@ActionFactory.register(name=BrowserAction.SEARCH_GOOGLE.value.name,
desc=BrowserAction.SEARCH_GOOGLE.value.desc,
tool_name="browser")
class SearchGoogle(ExecutableAction):
def act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
logger.info(f"exec {BrowserAction.SEARCH_GOOGLE.value.name} action")
page = get_page(**kwargs)
if page is None:
logger.warning(f"{BrowserAction.SEARCH_GOOGLE.name} page is none")
return ActionResult(content="search no page", keep=True), page
query = action.params.get("query")
page.goto(f'{SEARCH_ENGINE.get("")}{query}')
page.wait_for_load_state()
msg = f'Searched for "{query}" in Google'
logger.info(msg)
return ActionResult(content=msg, keep=True), page
async def async_act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
logger.info(f"exec {BrowserAction.SEARCH_GOOGLE.value.name} action")
page = get_page(**kwargs)
if page is None:
logger.warning(f"{BrowserAction.SEARCH_GOOGLE.name} page is none")
return ActionResult(content="search no page", keep=True), page
query = action.params.get("query")
await page.goto(f'{SEARCH_ENGINE.get("")}{query}')
await page.wait_for_load_state()
msg = f'Searched for "{query}" in Google'
logger.info(msg)
return ActionResult(content=msg, keep=True), page
@ActionFactory.register(name=BrowserAction.NEW_TAB.value.name,
desc=BrowserAction.NEW_TAB.value.desc,
tool_name="browser")
class NewTab(ExecutableAction):
def act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
logger.info(f"exec {BrowserAction.NEW_TAB.value.name} action")
browser = get_browser(**kwargs)
url = action.params.get("url")
new_page = browser.new_page()
new_page.wait_for_load_state()
if url:
new_page.goto(url)
DomUtil.wait_for_stable_network(new_page)
msg = f'Opened new tab with {url}'
logger.debug(msg)
return ActionResult(content=msg, keep=True), new_page
async def async_act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
logger.info(f"exec {BrowserAction.NEW_TAB.value.name} action")
browser = get_browser(**kwargs)
url = action.params.get("url")
new_page = await browser.new_page()
await new_page.wait_for_load_state()
if url:
await new_page.goto(url)
DomUtil.wait_for_stable_network(new_page)
msg = f'Opened new tab with {url}'
logger.debug(msg)
return ActionResult(content=msg, keep=True), get_page(**kwargs)
@ActionFactory.register(name=BrowserAction.GO_BACK.value.name,
desc=BrowserAction.GO_BACK.value.desc,
tool_name="browser")
class GoBack(ExecutableAction):
def act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
logger.info(f"exec {BrowserAction.GO_BACK.value.name} action")
page = get_page(**kwargs)
if page is None:
logger.warning(f"{BrowserAction.GO_BACK.name} page is none")
return ActionResult(content="search no page", keep=True), page
page.go_back()
msg = 'Navigated back'
logger.info(msg)
return ActionResult(content=msg, keep=True), page
async def async_act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
logger.info(f"exec {BrowserAction.GO_BACK.value.name} action")
page = get_page(**kwargs)
if page is None:
logger.warning(f"{BrowserAction.GO_BACK.name} page is none")
return ActionResult(content="search no page", keep=True), page
await page.go_back()
msg = 'Navigated back'
logger.info(msg)
return ActionResult(content=msg, keep=True), page
@ActionFactory.register(name=BrowserAction.EXTRACT_CONTENT.value.name,
desc=BrowserAction.EXTRACT_CONTENT.value.desc,
tool_name="browser")
class ExtractContent(ExecutableAction):
def act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
import markdownify
from langchain_core.prompts import PromptTemplate
logger.info(f"exec {BrowserAction.EXTRACT_CONTENT.value.name} action")
page = get_page(**kwargs)
if page is None:
logger.warning(f"{BrowserAction.EXTRACT_CONTENT.name} page is none")
return ActionResult(content="extract content no page", keep=True), page
goal = action.params.get("goal")
llm_config = kwargs.get("llm_config")
if llm_config and llm_config.llm_api_key:
llm = get_llm_model(llm_config)
max_extract_content_output_tokens = kwargs.get("max_extract_content_output_tokens")
max_extract_content_input_tokens = kwargs.get("max_extract_content_input_tokens")
content = markdownify.markdownify(page.content())
# Truncate content if it exceeds max input tokens
if max_extract_content_input_tokens and len(content) > max_extract_content_input_tokens:
logger.warning(
f"Content length ({len(content)}) exceeds max input tokens ({max_extract_content_input_tokens}). Truncating content.")
content = content[:max_extract_content_input_tokens]
prompt = 'Your task is to extract the content of the page. You will be given a page and a goal and you should extract all relevant information around this goal from the page. If the goal is vague, summarize the page. Respond in json format. Extraction goal: {goal}, Page: {page}'
prompt_with_outputlimit = 'Your task is to extract the content of the page. You will be given a page and a goal and you should extract all relevant information around this goal from the page. If the goal is vague, summarize the page. Respond in json format. Extraction goal: {goal}, Page: {page} \n\n#The length of the returned result must be less than {max_extract_content_output_tokens} characters.'
template = PromptTemplate(input_variables=['goal', 'page'], template=prompt)
messages = [{'role': 'user', 'content': template.format(goal=goal, page=content)}]
try:
output = call_llm_model(llm,
messages=messages,
model=llm_config.llm_model_name,
temperature=llm_config.llm_temperature)
result_content = output.content
# Check if output exceeds the token limit and retry with length-limited prompt if needed
if max_extract_content_output_tokens and len(result_content) > max_extract_content_output_tokens:
logger.warning(
f"Output exceeds maximum length ({len(result_content)} > {max_extract_content_output_tokens}). Retrying with limited prompt.")
template_with_limit = PromptTemplate(
input_variables=['goal', 'page', 'max_extract_content_output_tokens'],
template=prompt_with_outputlimit
)
messages = [{'role': 'user', 'content': template_with_limit.format(
goal=goal,
page=content,
max_extract_content_output_tokens=max_extract_content_output_tokens,
max_tokens=max_extract_content_output_tokens
)}]
# extract content with length limit
output = call_llm_model(llm,
messages=messages,
model=llm_config.llm_model_name,
temperature=llm_config.llm_temperature)
result_content = output.content
msg = f'Extracted from page\n: {result_content}\n'
logger.info(msg)
return ActionResult(content=msg, keep=True), page
except Exception as e:
logger.debug(f'Error extracting content: {e}')
msg = f'Extracted from page\n: {content}\n'
logger.info(msg)
return ActionResult(content=msg), page
async def async_act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
import markdownify
from langchain_core.prompts import PromptTemplate
logger.info(f"exec {BrowserAction.EXTRACT_CONTENT.value.name} action")
page = get_page(**kwargs)
if page is None:
logger.warning(f"{BrowserAction.EXTRACT_CONTENT.name} page is none")
return ActionResult(content="extract content no page", keep=True), page
goal = action.params.get("goal")
llm_config = kwargs.get("llm_config")
if llm_config and llm_config.llm_api_key:
llm = get_llm_model(llm_config)
content = markdownify.markdownify(await page.content())
max_extract_content_output_tokens = kwargs.get("max_extract_content_output_tokens")
max_extract_content_input_tokens = kwargs.get("max_extract_content_input_tokens")
# Truncate content if it exceeds max input tokens
if max_extract_content_input_tokens and len(content) > max_extract_content_input_tokens:
logger.warning(
f"Content length ({len(content)}) exceeds max input tokens ({max_extract_content_input_tokens}). Truncating content.")
content = content[:max_extract_content_input_tokens]
prompt = 'Your task is to extract the content of the page. You will be given a page and a goal and you should extract all relevant information around this goal from the page. If the goal is vague, summarize the page. Respond in json format. Extraction goal: {goal}, Page: {page}'
prompt_with_outputlimit = 'Your task is to extract the content of the page. You will be given a page and a goal and you should extract all relevant information around this goal from the page. If the goal is vague, summarize the page. Respond in json format. Extraction goal: {goal}, Page: {page} \n\n#The length of the returned result must be less than {max_extract_content_output_tokens} characters.'
template = PromptTemplate(input_variables=['goal', 'page'], template=prompt)
messages = [{'role': 'user', 'content': template.format(goal=goal, page=content)}]
try:
output = call_llm_model(llm,
messages=messages,
model=llm_config.llm_model_name,
temperature=llm_config.llm_temperature)
result_content = output.content
# Check if output exceeds the token limit and retry with length-limited prompt if needed
if max_extract_content_output_tokens and len(result_content) > max_extract_content_output_tokens:
logger.info(
f"Output exceeds maximum length ({len(result_content)} > {max_extract_content_output_tokens}). Retrying with limited prompt.")
template_with_limit = PromptTemplate(
input_variables=['goal', 'page', 'max_extract_content_output_tokens'],
template=prompt_with_outputlimit
)
messages = [{'role': 'user', 'content': template_with_limit.format(
goal=goal,
page=content,
max_extract_content_output_tokens=max_extract_content_output_tokens,
max_tokens=max_extract_content_output_tokens
)}]
# extract content with length limit
output = call_llm_model(llm,
messages=messages,
model=llm_config.llm_model_name,
temperature=llm_config.llm_temperature)
result_content = output.content
msg = f'Extracted from page\n: {result_content}\n'
logger.info(msg)
return ActionResult(content=msg, keep=True), page
except Exception as e:
logger.debug(f'Error extracting content: {e}')
msg = f'Extracted from page\n: {content}\n'
logger.info(msg)
return ActionResult(content=msg), page
@ActionFactory.register(name=BrowserAction.SCROLL_DOWN.value.name,
desc=BrowserAction.SCROLL_DOWN.value.desc,
tool_name="browser")
class ScrollDown(ExecutableAction):
def act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
logger.info(f"exec {BrowserAction.SCROLL_DOWN.value.name} action")
page = get_page(**kwargs)
if page is None:
logger.warning(f"{BrowserAction.SCROLL_DOWN.name} page is none")
return ActionResult(content="scroll no page", keep=True), page
amount = action.params.get("amount")
if not amount:
page.evaluate('window.scrollBy(0, window.innerHeight);')
else:
amount = int(amount)
page.evaluate(f'window.scrollBy(0, {amount});')
amount = f'{amount} pixels' if amount else 'one page'
msg = f'Scrolled down the page by {amount}'
logger.info(msg)
return ActionResult(content=msg, keep=True), page
async def async_act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
logger.info(f"exec {BrowserAction.SCROLL_DOWN.value.name} action")
page = get_page(**kwargs)
if page is None:
logger.warning(f"{BrowserAction.SCROLL_DOWN.name} page is none")
return ActionResult(content="scroll no page", keep=True), page
amount = action.params.get("amount")
if not amount:
await page.evaluate('window.scrollBy(0, window.innerHeight);')
else:
amount = int(amount)
await page.evaluate(f'window.scrollBy(0, {amount});')
amount = f'{amount} pixels' if amount else 'one page'
msg = f'Scrolled down the page by {amount}'
logger.info(msg)
return ActionResult(content=msg, keep=True), page
@ActionFactory.register(name=BrowserAction.SCROLL_UP.value.name,
desc=BrowserAction.SCROLL_UP.value.desc,
tool_name="browser")
class ScrollUp(ExecutableAction):
def act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
logger.info(f"exec {BrowserAction.SCROLL_UP.value.name} action")
page = get_page(**kwargs)
if page is None:
logger.warning(f"{BrowserAction.SCROLL_UP.name} page is none")
return ActionResult(content="scroll no page", keep=True), page
amount = action.params.get("amount")
if not amount:
page.evaluate('window.scrollBy(0, -window.innerHeight);')
else:
amount = int(amount)
page.evaluate(f'window.scrollBy(0, -{amount});')
amount = f'{amount} pixels' if amount else 'one page'
msg = f'Scrolled down the page by {amount}'
logger.info(msg)
return ActionResult(content=msg, keep=True), page
async def async_act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
logger.info(f"exec {BrowserAction.SCROLL_UP.value.name} action")
page = get_page(**kwargs)
if page is None:
logger.warning(f"{BrowserAction.SCROLL_UP.name} page is none")
return ActionResult(content="scroll no page", keep=True), page
amount = action.params.get("amount")
if not amount:
await page.evaluate('window.scrollBy(0, -window.innerHeight);')
else:
amount = int(amount)
await page.evaluate(f'window.scrollBy(0, -{amount});')
amount = f'{amount} pixels' if amount else 'one page'
msg = f'Scrolled down the page by {amount}'
logger.info(msg)
return ActionResult(content=msg, keep=True), page
@ActionFactory.register(name=BrowserAction.WAIT.value.name,
desc=BrowserAction.WAIT.value.desc,
tool_name="browser")
class Wait(ExecutableAction):
def act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
seconds = action.params.get("seconds")
if not seconds:
seconds = action.params.get("duration", 0)
seconds = int(seconds)
msg = f'Waiting for {seconds} seconds'
logger.info(msg)
time.sleep(seconds)
return ActionResult(content=msg, keep=True), kwargs.get('page')
async def async_act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
seconds = action.params.get("seconds")
if not seconds:
seconds = action.params.get("duration", 0)
seconds = int(seconds)
msg = f'Waiting for {seconds} seconds'
logger.info(msg)
await asyncio.sleep(seconds)
return ActionResult(content=msg, keep=True), kwargs.get('page')
@ActionFactory.register(name=BrowserAction.SWITCH_TAB.value.name,
desc=BrowserAction.SWITCH_TAB.value.desc,
tool_name="browser")
class SwitchTab(ExecutableAction):
def act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
logger.info(f"exec {BrowserAction.SWITCH_TAB.value.name} action")
browser = get_browser(**kwargs)
if browser is None:
logger.warning(f"{BrowserAction.SWITCH_TAB.name} browser context is none")
return ActionResult(content="switch tab no browser context", keep=True), get_page(**kwargs)
page_id = action.params.get("page_id", 0)
page_id = int(page_id)
pages = browser.pages
if page_id >= len(pages):
raise RuntimeError(f'No tab found with page_id: {page_id}')
page = pages[page_id]
page.bring_to_front()
page.wait_for_load_state()
msg = f'Switched to tab {page_id}'
logger.info(msg)
return ActionResult(content=msg, keep=True), page
async def async_act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
logger.info(f"exec {BrowserAction.SWITCH_TAB.value.name} action")
browser = get_browser(**kwargs)
if browser is None:
logger.warning(f"{BrowserAction.SWITCH_TAB.name} browser context is none")
return ActionResult(content="switch tab no browser context", keep=True), get_page(**kwargs)
page_id = action.params.get("page_id", 0)
page_id = int(page_id)
pages = browser.pages
if page_id >= len(pages):
raise RuntimeError(f'No tab found with page_id: {page_id}')
page = pages[page_id]
await page.bring_to_front()
await page.wait_for_load_state()
msg = f'Switched to tab {page_id}'
logger.info(msg)
return ActionResult(content=msg, keep=True), page
@ActionFactory.register(name=BrowserAction.SEND_KEYS.value.name,
desc=BrowserAction.SEND_KEYS.value.desc,
tool_name="browser")
class SendKeys(ExecutableAction):
def act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
logger.info(f"exec {BrowserAction.SEND_KEYS.value.name} action")
page = get_page(**kwargs)
if page is None:
logger.warning(f"{BrowserAction.SEND_KEYS.name} page is none")
return ActionResult(content="scroll no page", keep=True), page
keys = action.params.get("keys")
if not keys:
return ActionResult(success=False, content="no keys", keep=True), page
try:
page.keyboard.press(keys)
except Exception as e:
logger.warning(f"{keys} press fail. \n{traceback.format_exc()}")
raise e
return ActionResult(content=f"Sent keys: {keys}", keep=True), page
async def async_act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
logger.info(f"exec {BrowserAction.SEND_KEYS.value.name} action")
page = get_page(**kwargs)
if page is None:
logger.warning(f"{BrowserAction.SEND_KEYS.name} page is none")
return ActionResult(content="scroll no page", keep=True), page
keys = action.params.get("keys")
if not keys:
return ActionResult(success=False, content="no keys", keep=True), page
try:
await page.keyboard.press(keys)
except Exception as e:
logger.warning(f"{keys} press fail. \n{traceback.format_exc()}")
raise e
return ActionResult(content=f"Sent keys: {keys}", keep=True), page
@ActionFactory.register(name=BrowserAction.WRITE_TO_FILE.value.name,
desc=BrowserAction.WRITE_TO_FILE.value.desc,
tool_name="browser")
class WriteToFile(ExecutableAction):
def act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
# 设置默认文件路径
file_path = "tmp_result.md"
# 检查参数中是否有file_path
if "file_path" in action.params:
file_path = action.params.get("file_path", "tmp_result.md")
# 检查参数中是否有file_name
elif "file_name" in action.params:
file_path = action.params.get("file_name", "tmp_result.md")
elif "filename" in action.params:
file_path = action.params.get("filename", "tmp_result.md")
content = action.params.get("content", "")
mode = action.params.get("mode", "a") # Default to append mode
# 获取文件的绝对路径
abs_file_path = os.path.abspath(file_path)
try:
with open(file_path, mode, encoding='utf-8') as f:
f.write(content + '\n')
msg = f'Successfully wrote content to {abs_file_path}'
logger.info(msg)
return ActionResult(content=msg, keep=True), get_page(**kwargs)
except Exception as e:
error_msg = f'Failed to write to file {abs_file_path}: {str(e)}'
logger.error(error_msg)
return ActionResult(content=error_msg, keep=True, error=error_msg), get_page(**kwargs)
async def async_act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
# For file operations, we don't need to make this asynchronous
return self.act(action, **kwargs)
@ActionFactory.register(name=BrowserAction.DONE.value.name,
desc=BrowserAction.DONE.value.desc,
tool_name="browser")
class Done(ExecutableAction):
def act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
logger.info(f"exec {BrowserAction.DONE.value.name} action")
return ActionResult(is_done=True, success=True, content="done", keep=True), get_page(**kwargs)
async def async_act(self, action: ActionModel, **kwargs) -> Tuple[ActionResult, Any]:
logger.info(f"exec {BrowserAction.DONE.value.name} action")
return ActionResult(is_done=True, success=True, content="done", keep=True), get_page(**kwargs)
|