browsing_agent.py 7.9 KB

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