agent.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. from typing import Optional
  2. from agenthub.codeact_agent.codeact_agent import CodeActAgent
  3. from opendevin.controller import AgentController
  4. from opendevin.controller.agent import Agent
  5. from opendevin.controller.state.state import State
  6. from opendevin.core.config import SandboxConfig
  7. from opendevin.core.logger import opendevin_logger as logger
  8. from opendevin.events.stream import EventStream
  9. from opendevin.runtime import DockerSSHBox, get_runtime_cls
  10. from opendevin.runtime.runtime import Runtime
  11. from opendevin.runtime.server.runtime import ServerRuntime
  12. class AgentSession:
  13. """Represents a session with an agent.
  14. Attributes:
  15. controller: The AgentController instance for controlling the agent.
  16. """
  17. sid: str
  18. event_stream: EventStream
  19. controller: Optional[AgentController] = None
  20. runtime: Optional[Runtime] = None
  21. _closed: bool = False
  22. def __init__(self, sid):
  23. """Initializes a new instance of the Session class."""
  24. self.sid = sid
  25. self.event_stream = EventStream(sid)
  26. async def start(
  27. self,
  28. runtime_name: str,
  29. sandbox_config: SandboxConfig,
  30. agent: Agent,
  31. confirmation_mode: bool,
  32. max_iterations: int,
  33. ):
  34. """Starts the agent session.
  35. Args:
  36. start_event: The start event data (optional).
  37. """
  38. if self.controller or self.runtime:
  39. raise Exception(
  40. 'Session already started. You need to close this session and start a new one.'
  41. )
  42. await self._create_runtime(runtime_name, sandbox_config)
  43. await self._create_controller(agent, confirmation_mode, max_iterations)
  44. async def close(self):
  45. if self._closed:
  46. return
  47. if self.controller is not None:
  48. end_state = self.controller.get_state()
  49. end_state.save_to_session(self.sid)
  50. await self.controller.close()
  51. if self.runtime is not None:
  52. await self.runtime.close()
  53. self._closed = True
  54. async def _create_runtime(self, runtime_name: str, sandbox_config: SandboxConfig):
  55. """Creates a runtime instance."""
  56. if self.runtime is not None:
  57. raise Exception('Runtime already created')
  58. logger.info(f'Using runtime: {runtime_name}')
  59. runtime_cls = get_runtime_cls(runtime_name)
  60. self.runtime = runtime_cls(
  61. sandbox_config=sandbox_config, event_stream=self.event_stream, sid=self.sid
  62. )
  63. await self.runtime.ainit()
  64. async def _create_controller(
  65. self, agent: Agent, confirmation_mode: bool, max_iterations: int
  66. ):
  67. """Creates an AgentController instance."""
  68. if self.controller is not None:
  69. raise Exception('Controller already created')
  70. if self.runtime is None:
  71. raise Exception('Runtime must be initialized before the agent controller')
  72. logger.info(f'Creating agent {agent.name} using LLM {agent.llm.config.model}')
  73. if isinstance(agent, CodeActAgent):
  74. if not self.runtime or not (
  75. isinstance(self.runtime, ServerRuntime)
  76. and isinstance(self.runtime.sandbox, DockerSSHBox)
  77. ):
  78. logger.warning(
  79. 'CodeActAgent requires DockerSSHBox as sandbox! Using other sandbox that are not stateful'
  80. ' LocalBox will not work properly.'
  81. )
  82. self.runtime.init_sandbox_plugins(agent.sandbox_plugins)
  83. self.runtime.init_runtime_tools(agent.runtime_tools)
  84. self.controller = AgentController(
  85. sid=self.sid,
  86. event_stream=self.event_stream,
  87. agent=agent,
  88. max_iterations=int(max_iterations),
  89. confirmation_mode=confirmation_mode,
  90. )
  91. try:
  92. agent_state = State.restore_from_session(self.sid)
  93. self.controller.set_initial_state(agent_state)
  94. logger.info(f'Restored agent state from session, sid: {self.sid}')
  95. except Exception as e:
  96. print('Error restoring state', e)