main.py 9.4 KB

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