main.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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 config, get_llm_config_arg, parse_arguments
  10. from opendevin.core.logger import opendevin_logger as logger
  11. from opendevin.core.schema import AgentState
  12. from opendevin.events import EventSource, EventStream, EventStreamSubscriber
  13. from opendevin.events.action import MessageAction
  14. from opendevin.events.event import Event
  15. from opendevin.events.observation import AgentStateChangedObservation
  16. from opendevin.llm.llm import LLM
  17. from opendevin.runtime import get_runtime_cls
  18. from opendevin.runtime.sandbox import Sandbox
  19. def read_task_from_file(file_path: str) -> str:
  20. """Read task from the specified file."""
  21. with open(file_path, 'r', encoding='utf-8') as file:
  22. return file.read()
  23. def read_task_from_stdin() -> str:
  24. """Read task from stdin."""
  25. return sys.stdin.read()
  26. async def run_agent_controller(
  27. agent: Agent,
  28. task_str: str,
  29. max_iterations: int | None = None,
  30. max_budget_per_task: float | None = None,
  31. exit_on_message: bool = False,
  32. fake_user_response_fn: Callable[[State | None], str] | None = None,
  33. sandbox: Sandbox | None = None,
  34. runtime_tools_config: dict | None = None,
  35. sid: str | None = None,
  36. ) -> State | None:
  37. """Main coroutine to run the agent controller with task input flexibility.
  38. It's only used when you launch opendevin backend directly via cmdline.
  39. Args:
  40. task_str: The task to run.
  41. exit_on_message: quit if agent asks for a message from user (optional)
  42. fake_user_response_fn: An optional function that receives the current state (could be None) and returns a fake user response.
  43. sandbox: An optional sandbox to run the agent in.
  44. """
  45. # Logging
  46. logger.info(
  47. f'Running agent {agent.name}, model {agent.llm.model_name}, with task: "{task_str}"'
  48. )
  49. # set up the event stream
  50. cli_session = 'main' + ('_' + sid if sid else '')
  51. event_stream = EventStream(cli_session)
  52. # restore cli session if enabled
  53. initial_state = None
  54. if config.enable_cli_session:
  55. try:
  56. logger.info('Restoring agent state from cli session')
  57. initial_state = State.restore_from_session(cli_session)
  58. except Exception as e:
  59. print('Error restoring state', e)
  60. # init controller with this initial state
  61. controller = AgentController(
  62. agent=agent,
  63. max_iterations=max_iterations,
  64. max_budget_per_task=max_budget_per_task,
  65. event_stream=event_stream,
  66. initial_state=initial_state,
  67. )
  68. # runtime and tools
  69. runtime_cls = get_runtime_cls(config.runtime)
  70. runtime = runtime_cls(event_stream=event_stream, sandbox=sandbox)
  71. await runtime.ainit()
  72. runtime.init_sandbox_plugins(controller.agent.sandbox_plugins)
  73. runtime.init_runtime_tools(
  74. controller.agent.runtime_tools,
  75. is_async=False,
  76. runtime_tools_config=runtime_tools_config,
  77. )
  78. # browser eval specific
  79. # TODO: move to a better place
  80. if runtime.browser and runtime.browser.eval_dir:
  81. logger.info(f'Evaluation directory: {runtime.browser.eval_dir}')
  82. with open(
  83. os.path.join(runtime.browser.eval_dir, 'goal.txt'), 'r', encoding='utf-8'
  84. ) as f:
  85. task_str = f.read()
  86. logger.info(f'Dynamic Eval task: {task_str}')
  87. # start event is a MessageAction with the task, either resumed or new
  88. if config.enable_cli_session and initial_state is not None:
  89. # we're resuming the previous session
  90. event_stream.add_event(
  91. MessageAction(
  92. content="Let's get back on track. If you experienced errors before, do NOT resume your task. Ask me about it."
  93. ),
  94. EventSource.USER,
  95. )
  96. elif initial_state is None:
  97. # init with the provided task
  98. event_stream.add_event(MessageAction(content=task_str), EventSource.USER)
  99. async def on_event(event: Event):
  100. if isinstance(event, AgentStateChangedObservation):
  101. if event.agent_state == AgentState.AWAITING_USER_INPUT:
  102. if exit_on_message:
  103. message = '/exit'
  104. elif fake_user_response_fn is None:
  105. message = input('Request user input >> ')
  106. else:
  107. message = fake_user_response_fn(controller.get_state())
  108. action = MessageAction(content=message)
  109. event_stream.add_event(action, EventSource.USER)
  110. event_stream.subscribe(EventStreamSubscriber.MAIN, on_event)
  111. while controller.state.agent_state not in [
  112. AgentState.FINISHED,
  113. AgentState.REJECTED,
  114. AgentState.ERROR,
  115. AgentState.PAUSED,
  116. AgentState.STOPPED,
  117. ]:
  118. await asyncio.sleep(1) # Give back control for a tick, so the agent can run
  119. # save session when we're about to close
  120. if config.enable_cli_session:
  121. end_state = controller.get_state()
  122. end_state.save_to_session(cli_session)
  123. # close when done
  124. await controller.close()
  125. await runtime.close()
  126. return controller.get_state()
  127. if __name__ == '__main__':
  128. args = parse_arguments()
  129. # Determine the task
  130. if args.file:
  131. task_str = read_task_from_file(args.file)
  132. elif args.task:
  133. task_str = args.task
  134. elif not sys.stdin.isatty():
  135. task_str = read_task_from_stdin()
  136. else:
  137. raise ValueError('No task provided. Please specify a task through -t, -f.')
  138. # Override default LLM configs ([llm] section in config.toml)
  139. if args.llm_config:
  140. llm_config = get_llm_config_arg(args.llm_config)
  141. if llm_config is None:
  142. raise ValueError(f'Invalid toml file, cannot read {args.llm_config}')
  143. config.set_llm_config(llm_config)
  144. llm = LLM(llm_config=config.get_llm_config_from_agent(args.agent_cls))
  145. # Create the agent
  146. AgentCls: Type[Agent] = Agent.get_cls(args.agent_cls)
  147. agent = AgentCls(llm=llm)
  148. asyncio.run(
  149. run_agent_controller(
  150. agent=agent,
  151. task_str=task_str,
  152. max_iterations=args.max_iterations,
  153. max_budget_per_task=args.max_budget_per_task,
  154. )
  155. )