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.

component_factory.py 15 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. import os
  2. from pathlib import Path
  3. from typing import List, Literal, Union, Optional, Dict, Any, Type
  4. from datetime import datetime
  5. import json
  6. from autogen_agentchat.task import MaxMessageTermination, TextMentionTermination, StopMessageTermination
  7. import yaml
  8. import logging
  9. from packaging import version
  10. from ..datamodel import (
  11. TeamConfig, AgentConfig, ModelConfig, ToolConfig,
  12. TeamTypes, AgentTypes, ModelTypes, ToolTypes,
  13. ComponentType, ComponentConfig, ComponentConfigInput, TerminationConfig, TerminationTypes, Response
  14. )
  15. from autogen_agentchat.agents import AssistantAgent
  16. from autogen_agentchat.teams import RoundRobinGroupChat, SelectorGroupChat
  17. from autogen_ext.models import OpenAIChatCompletionClient
  18. from autogen_core.components.tools import FunctionTool
  19. logger = logging.getLogger(__name__)
  20. # Type definitions for supported components
  21. TeamComponent = Union[RoundRobinGroupChat, SelectorGroupChat]
  22. AgentComponent = Union[AssistantAgent] # Will grow with more agent types
  23. # Will grow with more model types
  24. ModelComponent = Union[OpenAIChatCompletionClient]
  25. ToolComponent = Union[FunctionTool] # Will grow with more tool types
  26. TerminationComponent = Union[MaxMessageTermination,
  27. StopMessageTermination, TextMentionTermination]
  28. # Config type definitions
  29. Component = Union[TeamComponent, AgentComponent, ModelComponent, ToolComponent]
  30. ReturnType = Literal['object', 'dict', 'config']
  31. Component = Union[RoundRobinGroupChat, SelectorGroupChat,
  32. AssistantAgent, OpenAIChatCompletionClient, FunctionTool]
  33. class ComponentFactory:
  34. """Creates and manages agent components with versioned configuration loading"""
  35. SUPPORTED_VERSIONS = {
  36. ComponentType.TEAM: ["1.0.0"],
  37. ComponentType.AGENT: ["1.0.0"],
  38. ComponentType.MODEL: ["1.0.0"],
  39. ComponentType.TOOL: ["1.0.0"],
  40. ComponentType.TERMINATION: ["1.0.0"]
  41. }
  42. def __init__(self):
  43. self._model_cache: Dict[str, OpenAIChatCompletionClient] = {}
  44. self._tool_cache: Dict[str, FunctionTool] = {}
  45. self._last_cache_clear = datetime.now()
  46. async def load(self, component: ComponentConfigInput, return_type: ReturnType = 'object') -> Union[Component, dict, ComponentConfig]:
  47. """
  48. Universal loader for any component type
  49. Args:
  50. component: Component configuration (file path, dict, or ComponentConfig)
  51. return_type: Type of return value ('object', 'dict', or 'config')
  52. Returns:
  53. Component instance, config dict, or ComponentConfig based on return_type
  54. Raises:
  55. ValueError: If component type is unknown or version unsupported
  56. """
  57. try:
  58. # Load and validate config
  59. if isinstance(component, (str, Path)):
  60. component_dict = await self._load_from_file(component)
  61. config = self._dict_to_config(component_dict)
  62. elif isinstance(component, dict):
  63. config = self._dict_to_config(component)
  64. else:
  65. config = component
  66. # Validate version
  67. if not self._is_version_supported(config.component_type, config.version):
  68. raise ValueError(
  69. f"Unsupported version {config.version} for "
  70. f"component type {config.component_type}. "
  71. f"Supported versions: {self.SUPPORTED_VERSIONS[config.component_type]}"
  72. )
  73. # Return early if dict or config requested
  74. if return_type == 'dict':
  75. return config.model_dump()
  76. elif return_type == 'config':
  77. return config
  78. # Otherwise create and return component instance
  79. handlers = {
  80. ComponentType.TEAM: self.load_team,
  81. ComponentType.AGENT: self.load_agent,
  82. ComponentType.MODEL: self.load_model,
  83. ComponentType.TOOL: self.load_tool,
  84. ComponentType.TERMINATION: self.load_termination
  85. }
  86. handler = handlers.get(config.component_type)
  87. if not handler:
  88. raise ValueError(
  89. f"Unknown component type: {config.component_type}")
  90. return await handler(config)
  91. except Exception as e:
  92. logger.error(f"Failed to load component: {str(e)}")
  93. raise
  94. async def load_directory(self, directory: Union[str, Path], check_exists: bool = False, return_type: ReturnType = 'object') -> List[Union[Component, dict, ComponentConfig]]:
  95. """
  96. Import all component configurations from a directory.
  97. """
  98. components = []
  99. try:
  100. directory = Path(directory)
  101. # Using Path.iterdir() instead of os.listdir
  102. for path in list(directory.glob("*")):
  103. if path.suffix.lower().endswith(('.json', '.yaml', '.yml')):
  104. try:
  105. component = await self.load(path, return_type)
  106. components.append(component)
  107. except Exception as e:
  108. logger.info(
  109. f"Failed to load component: {str(e)}, {path}")
  110. return components
  111. except Exception as e:
  112. logger.info(f"Failed to load directory: {str(e)}")
  113. return components
  114. def _dict_to_config(self, config_dict: dict) -> ComponentConfig:
  115. """Convert dictionary to appropriate config type based on component_type"""
  116. if "component_type" not in config_dict:
  117. raise ValueError("component_type is required in configuration")
  118. config_types = {
  119. ComponentType.TEAM: TeamConfig,
  120. ComponentType.AGENT: AgentConfig,
  121. ComponentType.MODEL: ModelConfig,
  122. ComponentType.TOOL: ToolConfig,
  123. ComponentType.TERMINATION: TerminationConfig # Add mapping for termination
  124. }
  125. component_type = ComponentType(config_dict["component_type"])
  126. config_class = config_types.get(component_type)
  127. if not config_class:
  128. raise ValueError(f"Unknown component type: {component_type}")
  129. return config_class(**config_dict)
  130. async def load_termination(self, config: TerminationConfig) -> TerminationComponent:
  131. """Create termination condition instance from configuration."""
  132. try:
  133. if config.termination_type == TerminationTypes.MAX_MESSAGES:
  134. return MaxMessageTermination(max_messages=config.max_messages)
  135. elif config.termination_type == TerminationTypes.STOP_MESSAGE:
  136. return StopMessageTermination()
  137. elif config.termination_type == TerminationTypes.TEXT_MENTION:
  138. if not config.text:
  139. raise ValueError(
  140. "text parameter required for TextMentionTermination")
  141. return TextMentionTermination(text=config.text)
  142. else:
  143. raise ValueError(
  144. f"Unsupported termination type: {config.termination_type}")
  145. except Exception as e:
  146. logger.error(f"Failed to create termination condition: {str(e)}")
  147. raise ValueError(
  148. f"Termination condition creation failed: {str(e)}")
  149. async def load_team(self, config: TeamConfig) -> TeamComponent:
  150. """Create team instance from configuration."""
  151. default_selector_prompt = """You are in a role play game. The following roles are available:
  152. {roles}.
  153. Read the following conversation. Then select the next role from {participants} to play. Only return the role.
  154. {history}
  155. Read the above conversation. Then select the next role from {participants} to play. Only return the role.
  156. """
  157. try:
  158. # Load participants (agents)
  159. participants = []
  160. for participant in config.participants:
  161. agent = await self.load(participant)
  162. participants.append(agent)
  163. # Load model client if specified
  164. model_client = None
  165. if config.model_client:
  166. model_client = await self.load(config.model_client)
  167. # Load termination condition if specified
  168. termination = None
  169. if config.termination_condition:
  170. # Now we can use the universal load() method since termination is a proper component
  171. termination = await self.load(config.termination_condition)
  172. # Create team based on type
  173. if config.team_type == TeamTypes.ROUND_ROBIN:
  174. return RoundRobinGroupChat(
  175. participants=participants,
  176. termination_condition=termination
  177. )
  178. elif config.team_type == TeamTypes.SELECTOR:
  179. if not model_client:
  180. raise ValueError(
  181. "SelectorGroupChat requires a model_client")
  182. selector_prompt = config.selector_prompt if config.selector_prompt else default_selector_prompt
  183. return SelectorGroupChat(
  184. participants=participants,
  185. model_client=model_client,
  186. termination_condition=termination,
  187. selector_prompt=selector_prompt
  188. )
  189. else:
  190. raise ValueError(f"Unsupported team type: {config.team_type}")
  191. except Exception as e:
  192. logger.error(f"Failed to create team {config.name}: {str(e)}")
  193. raise ValueError(f"Team creation failed: {str(e)}")
  194. async def load_agent(self, config: AgentConfig) -> AgentComponent:
  195. """Create agent instance from configuration."""
  196. try:
  197. # Load model client if specified
  198. model_client = None
  199. if config.model_client:
  200. model_client = await self.load(config.model_client)
  201. system_message = config.system_message if config.system_message else "You are a helpful assistant"
  202. # Load tools if specified
  203. tools = []
  204. if config.tools:
  205. for tool_config in config.tools:
  206. tool = await self.load(tool_config)
  207. tools.append(tool)
  208. if config.agent_type == AgentTypes.ASSISTANT:
  209. return AssistantAgent(
  210. name=config.name,
  211. model_client=model_client,
  212. tools=tools,
  213. system_message=system_message
  214. )
  215. else:
  216. raise ValueError(
  217. f"Unsupported agent type: {config.agent_type}")
  218. except Exception as e:
  219. logger.error(f"Failed to create agent {config.name}: {str(e)}")
  220. raise ValueError(f"Agent creation failed: {str(e)}")
  221. async def load_model(self, config: ModelConfig) -> ModelComponent:
  222. """Create model instance from configuration."""
  223. try:
  224. # Check cache first
  225. cache_key = str(config.model_dump())
  226. if cache_key in self._model_cache:
  227. logger.debug(f"Using cached model for {config.model}")
  228. return self._model_cache[cache_key]
  229. if config.model_type == ModelTypes.OPENAI:
  230. model = OpenAIChatCompletionClient(
  231. model=config.model,
  232. api_key=config.api_key,
  233. base_url=config.base_url
  234. )
  235. self._model_cache[cache_key] = model
  236. return model
  237. else:
  238. raise ValueError(
  239. f"Unsupported model type: {config.model_type}")
  240. except Exception as e:
  241. logger.error(f"Failed to create model {config.model}: {str(e)}")
  242. raise ValueError(f"Model creation failed: {str(e)}")
  243. async def load_tool(self, config: ToolConfig) -> ToolComponent:
  244. """Create tool instance from configuration."""
  245. try:
  246. # Validate required fields
  247. if not all([config.name, config.description, config.content, config.tool_type]):
  248. raise ValueError("Tool configuration missing required fields")
  249. # Check cache first
  250. cache_key = str(config.model_dump())
  251. if cache_key in self._tool_cache:
  252. logger.debug(f"Using cached tool '{config.name}'")
  253. return self._tool_cache[cache_key]
  254. if config.tool_type == ToolTypes.PYTHON_FUNCTION:
  255. tool = FunctionTool(
  256. name=config.name,
  257. description=config.description,
  258. func=self._func_from_string(config.content)
  259. )
  260. self._tool_cache[cache_key] = tool
  261. return tool
  262. else:
  263. raise ValueError(f"Unsupported tool type: {config.tool_type}")
  264. except Exception as e:
  265. logger.error(f"Failed to create tool '{config.name}': {str(e)}")
  266. raise
  267. # Helper methods remain largely the same
  268. async def _load_from_file(self, path: Union[str, Path]) -> dict:
  269. """Load configuration from JSON or YAML file."""
  270. path = Path(path)
  271. if not path.exists():
  272. raise FileNotFoundError(f"Config file not found: {path}")
  273. try:
  274. with open(path) as f:
  275. if path.suffix == '.json':
  276. return json.load(f)
  277. elif path.suffix in ('.yml', '.yaml'):
  278. return yaml.safe_load(f)
  279. else:
  280. raise ValueError(f"Unsupported file format: {path.suffix}")
  281. except Exception as e:
  282. raise ValueError(f"Failed to load file {path}: {str(e)}")
  283. def _func_from_string(self, content: str) -> callable:
  284. """Convert function string to callable."""
  285. try:
  286. namespace = {}
  287. exec(content, namespace)
  288. for item in namespace.values():
  289. if callable(item) and not isinstance(item, type):
  290. return item
  291. raise ValueError("No function found in provided code")
  292. except Exception as e:
  293. raise ValueError(f"Failed to create function: {str(e)}")
  294. def _is_version_supported(self, component_type: ComponentType, ver: str) -> bool:
  295. """Check if version is supported for component type."""
  296. try:
  297. v = version.parse(ver)
  298. return ver in self.SUPPORTED_VERSIONS[component_type]
  299. except version.InvalidVersion:
  300. return False
  301. async def cleanup(self) -> None:
  302. """Cleanup resources and clear caches."""
  303. for model in self._model_cache.values():
  304. if hasattr(model, 'cleanup'):
  305. await model.cleanup()
  306. for tool in self._tool_cache.values():
  307. if hasattr(tool, 'cleanup'):
  308. await tool.cleanup()
  309. self._model_cache.clear()
  310. self._tool_cache.clear()
  311. self._last_cache_clear = datetime.now()
  312. logger.info("Cleared all component caches")