browsing_agent.py 7.8 KB

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