main.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. import asyncio
  2. import hashlib
  3. import json
  4. import os
  5. import sys
  6. import uuid
  7. from typing import Callable, Protocol, Type
  8. import openhands.agenthub # noqa F401 (we import this to get the agents registered)
  9. from openhands.controller import AgentController
  10. from openhands.controller.agent import Agent
  11. from openhands.controller.state.state import State
  12. from openhands.core.config import (
  13. AppConfig,
  14. get_llm_config_arg,
  15. load_app_config,
  16. parse_arguments,
  17. )
  18. from openhands.core.logger import openhands_logger as logger
  19. from openhands.core.schema import AgentState
  20. from openhands.events import EventSource, EventStream, EventStreamSubscriber
  21. from openhands.events.action import MessageAction
  22. from openhands.events.action.action import Action
  23. from openhands.events.event import Event
  24. from openhands.events.observation import AgentStateChangedObservation
  25. from openhands.events.serialization.event import event_to_trajectory
  26. from openhands.llm.llm import LLM
  27. from openhands.runtime import get_runtime_cls
  28. from openhands.runtime.base import Runtime
  29. from openhands.storage import get_file_store
  30. class FakeUserResponseFunc(Protocol):
  31. def __call__(
  32. self,
  33. state: State,
  34. encapsulate_solution: bool = ...,
  35. try_parse: Callable[[Action], str] = ...,
  36. ) -> str: ...
  37. def read_task_from_file(file_path: str) -> str:
  38. """Read task from the specified file."""
  39. with open(file_path, 'r', encoding='utf-8') as file:
  40. return file.read()
  41. def read_task_from_stdin() -> str:
  42. """Read task from stdin."""
  43. return sys.stdin.read()
  44. def create_runtime(
  45. config: AppConfig,
  46. sid: str | None = None,
  47. ) -> Runtime:
  48. """Create a runtime for the agent to run on.
  49. config: The app config.
  50. sid: The session id.
  51. """
  52. # if sid is provided on the command line, use it as the name of the event stream
  53. # otherwise generate it on the basis of the configured jwt_secret
  54. # we can do this better, this is just so that the sid is retrieved when we want to restore the session
  55. session_id = sid or generate_sid(config)
  56. # set up the event stream
  57. file_store = get_file_store(config.file_store, config.file_store_path)
  58. event_stream = EventStream(session_id, file_store)
  59. # agent class
  60. agent_cls = openhands.agenthub.Agent.get_cls(config.default_agent)
  61. # runtime and tools
  62. runtime_cls = get_runtime_cls(config.runtime)
  63. logger.debug(f'Initializing runtime: {runtime_cls.__name__}')
  64. runtime: Runtime = runtime_cls(
  65. config=config,
  66. event_stream=event_stream,
  67. sid=session_id,
  68. plugins=agent_cls.sandbox_plugins,
  69. )
  70. return runtime
  71. async def run_controller(
  72. config: AppConfig,
  73. initial_user_action: Action,
  74. sid: str | None = None,
  75. runtime: Runtime | None = None,
  76. agent: Agent | None = None,
  77. exit_on_message: bool = False,
  78. fake_user_response_fn: FakeUserResponseFunc | None = None,
  79. headless_mode: bool = True,
  80. ) -> State | None:
  81. """Main coroutine to run the agent controller with task input flexibility.
  82. It's only used when you launch openhands backend directly via cmdline.
  83. Args:
  84. config: The app config.
  85. initial_user_action: An Action object containing initial user input
  86. runtime: (optional) A runtime for the agent to run on.
  87. agent: (optional) A agent to run.
  88. exit_on_message: quit if agent asks for a message from user (optional)
  89. fake_user_response_fn: An optional function that receives the current state
  90. (could be None) and returns a fake user response.
  91. headless_mode: Whether the agent is run in headless mode.
  92. """
  93. # Create the agent
  94. if agent is None:
  95. agent_cls: Type[Agent] = Agent.get_cls(config.default_agent)
  96. agent_config = config.get_agent_config(config.default_agent)
  97. llm_config = config.get_llm_config_from_agent(config.default_agent)
  98. agent = agent_cls(
  99. llm=LLM(config=llm_config),
  100. config=agent_config,
  101. )
  102. # make sure the session id is set
  103. sid = sid or generate_sid(config)
  104. if runtime is None:
  105. runtime = create_runtime(config, sid=sid)
  106. await runtime.connect()
  107. event_stream = runtime.event_stream
  108. # restore cli session if enabled
  109. initial_state = None
  110. if config.enable_cli_session:
  111. try:
  112. logger.debug(f'Restoring agent state from cli session {event_stream.sid}')
  113. initial_state = State.restore_from_session(
  114. event_stream.sid, event_stream.file_store
  115. )
  116. except Exception as e:
  117. logger.debug(f'Error restoring state: {e}')
  118. # init controller with this initial state
  119. controller = AgentController(
  120. agent=agent,
  121. max_iterations=config.max_iterations,
  122. max_budget_per_task=config.max_budget_per_task,
  123. agent_to_llm_config=config.get_agent_to_llm_config_map(),
  124. event_stream=event_stream,
  125. initial_state=initial_state,
  126. headless_mode=headless_mode,
  127. )
  128. if controller is not None:
  129. controller.agent_task = asyncio.create_task(controller.start_step_loop())
  130. assert isinstance(
  131. initial_user_action, Action
  132. ), f'initial user actions must be an Action, got {type(initial_user_action)}'
  133. # Logging
  134. logger.debug(
  135. f'Agent Controller Initialized: Running agent {agent.name}, model '
  136. f'{agent.llm.config.model}, with actions: {initial_user_action}'
  137. )
  138. # start event is a MessageAction with the task, either resumed or new
  139. if config.enable_cli_session and initial_state is not None:
  140. # we're resuming the previous session
  141. event_stream.add_event(
  142. MessageAction(
  143. content=(
  144. "Let's get back on track. If you experienced errors before, do "
  145. 'NOT resume your task. Ask me about it.'
  146. ),
  147. ),
  148. EventSource.USER,
  149. )
  150. elif initial_state is None:
  151. # init with the provided actions
  152. event_stream.add_event(initial_user_action, EventSource.USER)
  153. async def on_event(event: Event):
  154. if isinstance(event, AgentStateChangedObservation):
  155. if event.agent_state == AgentState.AWAITING_USER_INPUT:
  156. if exit_on_message:
  157. message = '/exit'
  158. elif fake_user_response_fn is None:
  159. message = input('Request user input >> ')
  160. else:
  161. message = fake_user_response_fn(controller.get_state())
  162. action = MessageAction(content=message)
  163. event_stream.add_event(action, EventSource.USER)
  164. event_stream.subscribe(EventStreamSubscriber.MAIN, on_event)
  165. while controller.state.agent_state not in [
  166. AgentState.FINISHED,
  167. AgentState.REJECTED,
  168. AgentState.ERROR,
  169. AgentState.PAUSED,
  170. AgentState.STOPPED,
  171. ]:
  172. await asyncio.sleep(1) # Give back control for a tick, so the agent can run
  173. # save session when we're about to close
  174. if config.enable_cli_session:
  175. end_state = controller.get_state()
  176. end_state.save_to_session(event_stream.sid, event_stream.file_store)
  177. # close when done
  178. await controller.close()
  179. state = controller.get_state()
  180. # save trajectories if applicable
  181. if config.trajectories_path is not None:
  182. file_path = os.path.join(config.trajectories_path, sid + '.json')
  183. os.makedirs(os.path.dirname(file_path), exist_ok=True)
  184. histories = [
  185. event_to_trajectory(event)
  186. for event in state.history.get_events(include_delegates=True)
  187. ]
  188. with open(file_path, 'w') as f:
  189. json.dump(histories, f)
  190. return state
  191. def generate_sid(config: AppConfig, session_name: str | None = None) -> str:
  192. """Generate a session id based on the session name and the jwt secret."""
  193. session_name = session_name or str(uuid.uuid4())
  194. jwt_secret = config.jwt_secret
  195. hash_str = hashlib.sha256(f'{session_name}{jwt_secret}'.encode('utf-8')).hexdigest()
  196. return f'{session_name}-{hash_str[:16]}'
  197. if __name__ == '__main__':
  198. args = parse_arguments()
  199. # Determine the task
  200. if args.file:
  201. task_str = read_task_from_file(args.file)
  202. elif args.task:
  203. task_str = args.task
  204. elif not sys.stdin.isatty():
  205. task_str = read_task_from_stdin()
  206. else:
  207. raise ValueError('No task provided. Please specify a task through -t, -f.')
  208. initial_user_action: MessageAction = MessageAction(content=task_str)
  209. # Load the app config
  210. # this will load config from config.toml in the current directory
  211. # as well as from the environment variables
  212. config = load_app_config(config_file=args.config_file)
  213. # Override default LLM configs ([llm] section in config.toml)
  214. if args.llm_config:
  215. llm_config = get_llm_config_arg(args.llm_config)
  216. if llm_config is None:
  217. raise ValueError(f'Invalid toml file, cannot read {args.llm_config}')
  218. config.set_llm_config(llm_config)
  219. # Set default agent
  220. config.default_agent = args.agent_cls
  221. # Set session name
  222. session_name = args.name
  223. sid = generate_sid(config, session_name)
  224. # if max budget per task is not sent on the command line, use the config value
  225. if args.max_budget_per_task is not None:
  226. config.max_budget_per_task = args.max_budget_per_task
  227. if args.max_iterations is not None:
  228. config.max_iterations = args.max_iterations
  229. asyncio.run(
  230. run_controller(
  231. config=config,
  232. initial_user_action=initial_user_action,
  233. sid=sid,
  234. )
  235. )