main.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. import asyncio
  2. import os
  3. import sys
  4. from typing import Callable, Type
  5. import agenthub # noqa F401 (we import this to get the agents registered)
  6. from opendevin.controller import AgentController
  7. from opendevin.controller.agent import Agent
  8. from opendevin.controller.state.state import State
  9. from opendevin.core.config import (
  10. AppConfig,
  11. get_llm_config_arg,
  12. load_app_config,
  13. parse_arguments,
  14. )
  15. from opendevin.core.logger import opendevin_logger as logger
  16. from opendevin.core.schema import AgentState
  17. from opendevin.events import EventSource, EventStream, EventStreamSubscriber
  18. from opendevin.events.action import MessageAction
  19. from opendevin.events.event import Event
  20. from opendevin.events.observation import AgentStateChangedObservation
  21. from opendevin.llm.llm import LLM
  22. from opendevin.runtime import get_runtime_cls
  23. from opendevin.runtime.sandbox import Sandbox
  24. from opendevin.runtime.server.runtime import ServerRuntime
  25. from opendevin.storage import get_file_store
  26. def read_task_from_file(file_path: str) -> str:
  27. """Read task from the specified file."""
  28. with open(file_path, 'r', encoding='utf-8') as file:
  29. return file.read()
  30. def read_task_from_stdin() -> str:
  31. """Read task from stdin."""
  32. return sys.stdin.read()
  33. async def run_controller(
  34. config: AppConfig,
  35. task_str: str,
  36. exit_on_message: bool = False,
  37. fake_user_response_fn: Callable[[State | None], str] | None = None,
  38. sandbox: Sandbox | None = None,
  39. agent: Agent | None = None,
  40. runtime_tools_config: dict | None = None,
  41. sid: str | None = None,
  42. headless_mode: bool = True,
  43. ) -> State | None:
  44. """Main coroutine to run the agent controller with task input flexibility.
  45. It's only used when you launch opendevin backend directly via cmdline.
  46. Args:
  47. config: The app config.
  48. task_str: The task to run.
  49. exit_on_message: quit if agent asks for a message from user (optional)
  50. fake_user_response_fn: An optional function that receives the current state (could be None) and returns a fake user response.
  51. sandbox: (will be deprecated) An optional sandbox to run the agent in.
  52. agent: An optional agent to run.
  53. runtime_tools_config: (will be deprecated) The runtime tools config.
  54. sid: The session id.
  55. headless_mode: Whether the agent is run in headless mode.
  56. """
  57. # Create the agent
  58. if agent is None:
  59. agent_cls: Type[Agent] = Agent.get_cls(config.default_agent)
  60. agent = agent_cls(
  61. llm=LLM(config=config.get_llm_config_from_agent(config.default_agent))
  62. )
  63. # Logging
  64. logger.info(
  65. f'Running agent {agent.name}, model {agent.llm.config.model}, with task: "{task_str}"'
  66. )
  67. # set up the event stream
  68. file_store = get_file_store(config.file_store, config.file_store_path)
  69. cli_session = 'main' + ('_' + sid if sid else '')
  70. event_stream = EventStream(cli_session, file_store)
  71. # restore cli session if enabled
  72. initial_state = None
  73. if config.enable_cli_session:
  74. try:
  75. logger.info('Restoring agent state from cli session')
  76. initial_state = State.restore_from_session(cli_session, file_store)
  77. except Exception as e:
  78. print('Error restoring state', e)
  79. # init controller with this initial state
  80. controller = AgentController(
  81. agent=agent,
  82. max_iterations=config.max_iterations,
  83. max_budget_per_task=config.max_budget_per_task,
  84. agent_to_llm_config=config.get_agent_to_llm_config_map(),
  85. event_stream=event_stream,
  86. initial_state=initial_state,
  87. headless_mode=headless_mode,
  88. )
  89. # runtime and tools
  90. runtime_cls = get_runtime_cls(config.runtime)
  91. extra_kwargs = {}
  92. if isinstance(runtime_cls, ServerRuntime):
  93. extra_kwargs['sandbox'] = sandbox
  94. # TODO: deprecate this and accept runtime as a parameter instead
  95. logger.info(f'Initializing runtime: {runtime_cls}')
  96. runtime = runtime_cls(
  97. config=config,
  98. event_stream=event_stream,
  99. plugins=controller.agent.sandbox_plugins,
  100. **extra_kwargs,
  101. )
  102. await runtime.ainit()
  103. if isinstance(runtime, ServerRuntime):
  104. runtime.init_runtime_tools(
  105. controller.agent.runtime_tools,
  106. runtime_tools_config=runtime_tools_config,
  107. )
  108. # browser eval specific
  109. # NOTE: This will be deprecated when we move to the new runtime
  110. if runtime.browser and runtime.browser.eval_dir:
  111. logger.info(f'Evaluation directory: {runtime.browser.eval_dir}')
  112. with open(
  113. os.path.join(runtime.browser.eval_dir, 'goal.txt'),
  114. 'r',
  115. encoding='utf-8',
  116. ) as f:
  117. task_str = f.read()
  118. logger.info(f'Dynamic Eval task: {task_str}')
  119. # TODO: Implement this for EventStream Runtime
  120. # start event is a MessageAction with the task, either resumed or new
  121. if config.enable_cli_session and initial_state is not None:
  122. # we're resuming the previous session
  123. event_stream.add_event(
  124. MessageAction(
  125. content="Let's get back on track. If you experienced errors before, do NOT resume your task. Ask me about it."
  126. ),
  127. EventSource.USER,
  128. )
  129. elif initial_state is None:
  130. # init with the provided task
  131. event_stream.add_event(MessageAction(content=task_str), EventSource.USER)
  132. async def on_event(event: Event):
  133. if isinstance(event, AgentStateChangedObservation):
  134. if event.agent_state == AgentState.AWAITING_USER_INPUT:
  135. if exit_on_message:
  136. message = '/exit'
  137. elif fake_user_response_fn is None:
  138. message = input('Request user input >> ')
  139. else:
  140. message = fake_user_response_fn(controller.get_state())
  141. action = MessageAction(content=message)
  142. event_stream.add_event(action, EventSource.USER)
  143. event_stream.subscribe(EventStreamSubscriber.MAIN, on_event)
  144. while controller.state.agent_state not in [
  145. AgentState.FINISHED,
  146. AgentState.REJECTED,
  147. AgentState.ERROR,
  148. AgentState.PAUSED,
  149. AgentState.STOPPED,
  150. ]:
  151. await asyncio.sleep(1) # Give back control for a tick, so the agent can run
  152. # save session when we're about to close
  153. if config.enable_cli_session:
  154. end_state = controller.get_state()
  155. end_state.save_to_session(cli_session, file_store)
  156. # close when done
  157. await controller.close()
  158. await runtime.close()
  159. return controller.get_state()
  160. if __name__ == '__main__':
  161. args = parse_arguments()
  162. # Determine the task
  163. if args.file:
  164. task_str = read_task_from_file(args.file)
  165. elif args.task:
  166. task_str = args.task
  167. elif not sys.stdin.isatty():
  168. task_str = read_task_from_stdin()
  169. else:
  170. raise ValueError('No task provided. Please specify a task through -t, -f.')
  171. # Load the app config
  172. # this will load config from config.toml in the current directory
  173. # as well as from the environment variables
  174. config = load_app_config()
  175. # Override default LLM configs ([llm] section in config.toml)
  176. if args.llm_config:
  177. llm_config = get_llm_config_arg(args.llm_config)
  178. if llm_config is None:
  179. raise ValueError(f'Invalid toml file, cannot read {args.llm_config}')
  180. config.set_llm_config(llm_config)
  181. # Set default agent
  182. config.default_agent = args.agent_cls
  183. # if max budget per task is not sent on the command line, use the config value
  184. if args.max_budget_per_task is not None:
  185. config.max_budget_per_task = args.max_budget_per_task
  186. if args.max_iterations is not None:
  187. config.max_iterations = args.max_iterations
  188. asyncio.run(
  189. run_controller(
  190. config=config,
  191. task_str=task_str,
  192. )
  193. )