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.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import time
  2. from typing import AsyncGenerator, Callable, Optional, Union
  3. from autogen_agentchat.base import TaskResult
  4. from autogen_agentchat.messages import AgentMessage, 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[AgentMessage, 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. except Exception as e:
  37. raise e
  38. async def run(
  39. self,
  40. task: str,
  41. team_config: ComponentConfigInput,
  42. input_func: Optional[Callable] = None,
  43. cancellation_token: Optional[CancellationToken] = None,
  44. ) -> TeamResult:
  45. """Original non-streaming run method with optional cancellation"""
  46. start_time = time.time()
  47. team = await self._create_team(team_config, input_func)
  48. result = await team.run(task=task, cancellation_token=cancellation_token)
  49. return self._create_result(result, start_time)