browsing_agent.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. import os
  2. from browsergym.core.action.highlevel import HighLevelActionSet
  3. from browsergym.utils.obs import flatten_axtree_to_str
  4. from agenthub.browsing_agent.response_parser import BrowsingResponseParser
  5. from openhands.controller.agent import Agent
  6. from openhands.controller.state.state import State
  7. from openhands.core.config import AgentConfig
  8. from openhands.core.logger import openhands_logger as logger
  9. from openhands.core.message import Message, TextContent
  10. from openhands.events.action import (
  11. Action,
  12. AgentFinishAction,
  13. BrowseInteractiveAction,
  14. MessageAction,
  15. )
  16. from openhands.events.event import EventSource
  17. from openhands.events.observation import BrowserOutputObservation
  18. from openhands.events.observation.observation import Observation
  19. from openhands.llm.llm import LLM
  20. from openhands.runtime.plugins import (
  21. PluginRequirement,
  22. )
  23. USE_NAV = (
  24. os.environ.get('USE_NAV', 'true') == 'true'
  25. ) # only disable NAV actions when running webarena and miniwob benchmarks
  26. USE_CONCISE_ANSWER = (
  27. os.environ.get('USE_CONCISE_ANSWER', 'false') == 'true'
  28. ) # only return concise answer when running webarena and miniwob benchmarks
  29. if not USE_NAV and USE_CONCISE_ANSWER:
  30. EVAL_MODE = True # disabled NAV actions and only return concise answer, for webarena and miniwob benchmarks\
  31. else:
  32. EVAL_MODE = False
  33. def get_error_prefix(last_browser_action: str) -> str:
  34. return f'IMPORTANT! Last action is incorrect:\n{last_browser_action}\nThink again with the current observation of the page.\n'
  35. def get_system_message(goal: str, action_space: str) -> str:
  36. return f"""\
  37. # Instructions
  38. Review the current state of the page and all other information to find the best
  39. possible next action to accomplish your goal. Your answer will be interpreted
  40. and executed by a program, make sure to follow the formatting instructions.
  41. # Goal:
  42. {goal}
  43. # Action Space
  44. {action_space}
  45. """
  46. CONCISE_INSTRUCTION = """\
  47. Here is another example with chain of thought of a valid action when providing a concise answer to user:
  48. "
  49. In order to accomplish my goal I need to send the information asked back to the user. This page list the information of HP Inkjet Fax Machine, which is the product identified in the objective. Its price is $279.49. I will send a message back to user with the answer.
  50. ```send_msg_to_user("$279.49")```
  51. "
  52. """
  53. def get_prompt(
  54. error_prefix: str, cur_url: str, cur_axtree_txt: str, prev_action_str: str
  55. ) -> str:
  56. prompt = f"""\
  57. {error_prefix}
  58. # Current Page URL:
  59. {cur_url}
  60. # Current Accessibility Tree:
  61. {cur_axtree_txt}
  62. # Previous Actions
  63. {prev_action_str}
  64. Here is an example with chain of thought of a valid action when clicking on a button:
  65. "
  66. In order to accomplish my goal I need to click on the button with bid 12
  67. ```click("12")```
  68. "
  69. """.strip()
  70. if USE_CONCISE_ANSWER:
  71. prompt += CONCISE_INSTRUCTION
  72. return prompt
  73. class BrowsingAgent(Agent):
  74. VERSION = '1.0'
  75. """
  76. An agent that interacts with the browser.
  77. """
  78. sandbox_plugins: list[PluginRequirement] = []
  79. response_parser = BrowsingResponseParser()
  80. def __init__(
  81. self,
  82. llm: LLM,
  83. config: AgentConfig,
  84. ) -> None:
  85. """Initializes a new instance of the BrowsingAgent class.
  86. Parameters:
  87. - llm (LLM): The llm to be used by this agent
  88. """
  89. super().__init__(llm, config)
  90. # define a configurable action space, with chat functionality, web navigation, and webpage grounding using accessibility tree and HTML.
  91. # see https://github.com/ServiceNow/BrowserGym/blob/main/core/src/browsergym/core/action/highlevel.py for more details
  92. action_subsets = ['chat', 'bid']
  93. if USE_NAV:
  94. action_subsets.append('nav')
  95. self.action_space = HighLevelActionSet(
  96. subsets=action_subsets,
  97. strict=False, # less strict on the parsing of the actions
  98. multiaction=True, # enable to agent to take multiple actions at once
  99. )
  100. self.reset()
  101. def reset(self) -> None:
  102. """Resets the Browsing Agent."""
  103. super().reset()
  104. self.cost_accumulator = 0
  105. self.error_accumulator = 0
  106. def step(self, state: State) -> Action:
  107. """Performs one step using the Browsing Agent.
  108. This includes gathering information on previous steps and prompting the model to make a browsing command to execute.
  109. Parameters:
  110. - state (State): used to get updated info
  111. Returns:
  112. - BrowseInteractiveAction(browsergym_command) - BrowserGym commands to run
  113. - MessageAction(content) - Message action to run (e.g. ask for clarification)
  114. - AgentFinishAction() - end the interaction
  115. """
  116. messages: list[Message] = []
  117. prev_actions = []
  118. cur_url = ''
  119. cur_axtree_txt = ''
  120. error_prefix = ''
  121. last_obs = None
  122. last_action = None
  123. if EVAL_MODE and len(state.history.get_events_as_list()) == 1:
  124. # for webarena and miniwob++ eval, we need to retrieve the initial observation already in browser env
  125. # initialize and retrieve the first observation by issuing an noop OP
  126. # For non-benchmark browsing, the browser env starts with a blank page, and the agent is expected to first navigate to desired websites
  127. return BrowseInteractiveAction(browser_actions='noop()')
  128. for event in state.history.get_events():
  129. if isinstance(event, BrowseInteractiveAction):
  130. prev_actions.append(event.browser_actions)
  131. last_action = event
  132. elif isinstance(event, MessageAction) and event.source == EventSource.AGENT:
  133. # agent has responded, task finished.
  134. return AgentFinishAction(outputs={'content': event.content})
  135. elif isinstance(event, Observation):
  136. last_obs = event
  137. if EVAL_MODE:
  138. prev_actions = prev_actions[1:] # remove the first noop action
  139. prev_action_str = '\n'.join(prev_actions)
  140. # if the final BrowserInteractiveAction exec BrowserGym's send_msg_to_user,
  141. # we should also send a message back to the user in OpenHands and call it a day
  142. if (
  143. isinstance(last_action, BrowseInteractiveAction)
  144. and last_action.browsergym_send_msg_to_user
  145. ):
  146. return MessageAction(last_action.browsergym_send_msg_to_user)
  147. if isinstance(last_obs, BrowserOutputObservation):
  148. if last_obs.error:
  149. # add error recovery prompt prefix
  150. error_prefix = get_error_prefix(last_obs.last_browser_action)
  151. self.error_accumulator += 1
  152. if self.error_accumulator > 5:
  153. return MessageAction('Too many errors encountered. Task failed.')
  154. cur_url = last_obs.url
  155. try:
  156. cur_axtree_txt = flatten_axtree_to_str(
  157. last_obs.axtree_object,
  158. extra_properties=last_obs.extra_element_properties,
  159. with_clickable=True,
  160. filter_visible_only=True,
  161. )
  162. except Exception as e:
  163. logger.error(
  164. 'Error when trying to process the accessibility tree: %s', e
  165. )
  166. return MessageAction('Error encountered when browsing.')
  167. goal, _ = state.get_current_user_intent()
  168. if goal is None:
  169. goal = state.inputs['task']
  170. system_msg = get_system_message(
  171. goal,
  172. self.action_space.describe(with_long_description=False, with_examples=True),
  173. )
  174. messages.append(Message(role='system', content=[TextContent(text=system_msg)]))
  175. prompt = get_prompt(error_prefix, cur_url, cur_axtree_txt, prev_action_str)
  176. messages.append(Message(role='user', content=[TextContent(text=prompt)]))
  177. response = self.llm.completion(
  178. messages=self.llm.format_messages_for_llm(messages),
  179. stop=[')```', ')\n```'],
  180. )
  181. return self.response_parser.parse(response)