You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

teammanager.py 2.7 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import time
  2. from typing import AsyncGenerator, Callable, Optional, Union
  3. from autogen_agentchat.base import TaskResult
  4. from autogen_agentchat.messages import AgentEvent, ChatMessage
  5. from autogen_core import CancellationToken
  6. from .database import Component, ComponentFactory
  7. from .datamodel import ComponentConfigInput, TeamResult
  8. class TeamManager:
  9. def __init__(self) -> None:
  10. self.component_factory = ComponentFactory()
  11. async def _create_team(self, team_config: ComponentConfigInput, input_func: Optional[Callable] = None) -> Component:
  12. """Create team instance with common setup logic"""
  13. return await self.component_factory.load(team_config, input_func=input_func)
  14. def _create_result(self, task_result: TaskResult, start_time: float) -> TeamResult:
  15. """Create TeamResult with timing info"""
  16. return TeamResult(task_result=task_result, usage="", duration=time.time() - start_time)
  17. async def run_stream(
  18. self,
  19. task: str,
  20. team_config: ComponentConfigInput,
  21. input_func: Optional[Callable] = None,
  22. cancellation_token: Optional[CancellationToken] = None,
  23. ) -> AsyncGenerator[Union[AgentEvent | ChatMessage, ChatMessage, TaskResult], None]:
  24. """Stream the team's execution results"""
  25. start_time = time.time()
  26. try:
  27. team = await self._create_team(team_config, input_func)
  28. stream = team.run_stream(task=task, cancellation_token=cancellation_token)
  29. async for message in stream:
  30. if cancellation_token and cancellation_token.is_cancelled():
  31. break
  32. if isinstance(message, TaskResult):
  33. yield self._create_result(message, start_time)
  34. else:
  35. yield message
  36. # close agent resources
  37. for agent in team._participants:
  38. if hasattr(agent, "close"):
  39. await agent.close()
  40. except Exception as e:
  41. raise e
  42. async def run(
  43. self,
  44. task: str,
  45. team_config: ComponentConfigInput,
  46. input_func: Optional[Callable] = None,
  47. cancellation_token: Optional[CancellationToken] = None,
  48. ) -> TeamResult:
  49. """Original non-streaming run method with optional cancellation"""
  50. start_time = time.time()
  51. team = await self._create_team(team_config, input_func)
  52. result = await team.run(task=task, cancellation_token=cancellation_token)
  53. # close agent resources
  54. for agent in team._participants:
  55. if hasattr(agent, "close"):
  56. await agent.close()
  57. return self._create_result(result, start_time)