main.py 7.4 KB

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