A programming framework for agentic AI
Update AGS to Use AgentChat Declarative Config Serialization (#5261)
Victor Dibiab2800d729b28
diff --git a/python/packages/autogen-core/docs/src/user-guide/autogenstudio-user-guide/usage.md b/python/packages/autogen-core/docs/src/user-guide/autogenstudio-user-guide/usage.mdindex 6c5a0251d..e185a9128 100644--- a/python/packages/autogen-core/docs/src/user-guide/autogenstudio-user-guide/usage.md+++ b/python/packages/autogen-core/docs/src/user-guide/autogenstudio-user-guide/usage.md@@ -14,43 +14,89 @@ After defining a team, users can test it in the Playground view to accomplish va## Declarative Specification of Componenents-AutoGen Studio uses a declarative specification system to build its GUI components. At runtime, the AGS API loads these specifications into AutoGen AgentChat objects to address tasks.+AutoGen Studio is built on the declarative specification behaviors of AutoGen AgentChat. This allows users to define teams, agents, models, tools, and termination conditions in python and then dump them into a JSON file for use in AutoGen Studio.-Here's an example of a declarative team specification:+Here's an example of an agent team and how it is converted to a JSON file:++```python+from autogen_agentchat.agents import AssistantAgent+from autogen_agentchat.teams import RoundRobinGroupChat+from autogen_ext.models.openai import OpenAIChatCompletionClient+from autogen_agentchat.conditions import TextMentionTermination++agent = AssistantAgent(+ name="weather_agent",+ model_client=OpenAIChatCompletionClient(+ model="gpt-4o-mini",+ ),+ )++agent_team = RoundRobinGroupChat([agent], termination_condition=TextMentionTermination("TERMINATE"))+config = agent_team.dump_component()+print(config.model_dump_json())+``````json{- "version": "1.0.0",+ "provider": "autogen_agentchat.teams.RoundRobinGroupChat","component_type": "team",- "name": "sample_team",- "participants": [- {- "component_type": "agent",- "name": "assistant_agent",- "agent_type": "AssistantAgent",- "system_message": "You are a helpful assistant. Solve tasks carefully. When done respond with TERMINATE",- "model_client": {- "component_type": "model",- "model": "gpt-4o-2024-08-06",- "model_type": "OpenAIChatCompletionClient"- },- "tools": []+ "version": 1,+ "component_version": 1,+ "description": "A team that runs a group chat with participants taking turns in a round-robin fashion\n to publish a message to all.",+ "label": "RoundRobinGroupChat",+ "config": {+ "participants": [+ {+ "provider": "autogen_agentchat.agents.AssistantAgent",+ "component_type": "agent",+ "version": 1,+ "component_version": 1,+ "description": "An agent that provides assistance with tool use.",+ "label": "AssistantAgent",+ "config": {+ "name": "weather_agent",+ "model_client": {+ "provider": "autogen_ext.models.openai.OpenAIChatCompletionClient",+ "component_type": "model",+ "version": 1,+ "component_version": 1,+ "description": "Chat completion client for OpenAI hosted models.",+ "label": "OpenAIChatCompletionClient",+ "config": { "model": "gpt-4o-mini" }+ },+ "tools": [],+ "handoffs": [],+ "model_context": {+ "provider": "autogen_core.model_context.UnboundedChatCompletionContext",+ "component_type": "chat_completion_context",+ "version": 1,+ "component_version": 1,+ "description": "An unbounded chat completion context that keeps a view of the all the messages.",+ "label": "UnboundedChatCompletionContext",+ "config": {}+ },+ "description": "An agent that provides assistance with ability to use tools.",+ "system_message": "You are a helpful AI assistant. Solve tasks using your tools. Reply with TERMINATE when the task has been completed.",+ "model_client_stream": false,+ "reflect_on_tool_use": false,+ "tool_call_summary_format": "{result}"+ }+ }+ ],+ "termination_condition": {+ "provider": "autogen_agentchat.conditions.TextMentionTermination",+ "component_type": "termination",+ "version": 1,+ "component_version": 1,+ "description": "Terminate the conversation if a specific text is mentioned.",+ "label": "TextMentionTermination",+ "config": { "text": "TERMINATE" }}- ],- "team_type": "RoundRobinGroupChat",- "termination_condition": {- "component_type": "termination",- "termination_type": "MaxMessageTermination",- "max_messages": 3}}```-This example shows a team with a single agent, using the `RoundRobinGroupChat` type and a `MaxMessageTermination` condition limited to 3 messages.--```{note}-Work is currently in progress to make the entire AgentChat API declarative. This will allow all agentchat components to be `dumped` into the same declarative specification format used by AGS.-```+This example shows a team with a single agent, using the `RoundRobinGroupChat` type and a `TextMentionTermination` condition.## Building an Agent Teamdiff --git a/python/packages/autogen-studio/autogenstudio/__init__.py b/python/packages/autogen-studio/autogenstudio/__init__.pyindex 137cbad5a..f67d1562d 100644--- a/python/packages/autogen-studio/autogenstudio/__init__.py+++ b/python/packages/autogen-studio/autogenstudio/__init__.py@@ -1,18 +1,6 @@from .database.db_manager import DatabaseManager-from .datamodel import Agent, AgentConfig, Model, ModelConfig, Team, TeamConfig, Tool, ToolConfig+from .datamodel import Teamfrom .teammanager import TeamManagerfrom .version import __version__-__all__ = [- "Tool",- "Model",- "DatabaseManager",- "Team",- "Agent",- "ToolConfig",- "ModelConfig",- "TeamConfig",- "AgentConfig",- "TeamManager",- "__version__",-]+__all__ = ["DatabaseManager", "Team", "TeamManager", "__version__"]diff --git a/python/packages/autogen-studio/autogenstudio/database/__init__.py b/python/packages/autogen-studio/autogenstudio/database/__init__.pyindex acdf58355..be859be0a 100644--- a/python/packages/autogen-studio/autogenstudio/database/__init__.py+++ b/python/packages/autogen-studio/autogenstudio/database/__init__.py@@ -1,3 +1,6 @@-from .component_factory import Component, ComponentFactory-from .config_manager import ConfigurationManagerfrom .db_manager import DatabaseManager+from .gallery_builder import GalleryBuilder, create_default_gallery++__all__ = [+ "DatabaseManager",+]diff --git a/python/packages/autogen-studio/autogenstudio/database/component_factory.py b/python/packages/autogen-studio/autogenstudio/database/component_factory.pydeleted file mode 100644index b954b39c0..000000000--- a/python/packages/autogen-studio/autogenstudio/database/component_factory.py+++ /dev/null@@ -1,503 +0,0 @@-import json-import logging-from datetime import datetime-from pathlib import Path-from typing import Callable, Dict, List, Literal, Optional, Union--import aiofiles-import yaml-from autogen_agentchat.agents import AssistantAgent, UserProxyAgent-from autogen_agentchat.conditions import (- ExternalTermination,- HandoffTermination,- MaxMessageTermination,- SourceMatchTermination,- StopMessageTermination,- TextMentionTermination,- TimeoutTermination,- TokenUsageTermination,-)-from autogen_agentchat.teams import MagenticOneGroupChat, RoundRobinGroupChat, SelectorGroupChat-from autogen_core.tools import FunctionTool-from autogen_ext.agents.file_surfer import FileSurfer-from autogen_ext.agents.magentic_one import MagenticOneCoderAgent-from autogen_ext.agents.web_surfer import MultimodalWebSurfer-from autogen_ext.models.openai import AzureOpenAIChatCompletionClient, OpenAIChatCompletionClient--from ..datamodel.types import (- AgentConfig,- AgentTypes,- AssistantAgentConfig,- AzureOpenAIModelConfig,- CombinationTerminationConfig,- ComponentConfig,- ComponentConfigInput,- ComponentTypes,- MagenticOneTeamConfig,- MaxMessageTerminationConfig,- ModelConfig,- ModelTypes,- MultimodalWebSurferAgentConfig,- OpenAIModelConfig,- RoundRobinTeamConfig,- SelectorTeamConfig,- TeamConfig,- TeamTypes,- TerminationConfig,- TerminationTypes,- TextMentionTerminationConfig,- ToolConfig,- ToolTypes,- UserProxyAgentConfig,-)-from ..utils.utils import Version--logger = logging.getLogger(__name__)--TeamComponent = Union[RoundRobinGroupChat, SelectorGroupChat, MagenticOneGroupChat]-AgentComponent = Union[AssistantAgent, MultimodalWebSurfer, UserProxyAgent, FileSurfer, MagenticOneCoderAgent]-ModelComponent = Union[OpenAIChatCompletionClient, AzureOpenAIChatCompletionClient]-ToolComponent = Union[FunctionTool] # Will grow with more tool types-TerminationComponent = Union[- MaxMessageTermination,- StopMessageTermination,- TextMentionTermination,- TimeoutTermination,- ExternalTermination,- TokenUsageTermination,- HandoffTermination,- SourceMatchTermination,- StopMessageTermination,-]--Component = Union[TeamComponent, AgentComponent, ModelComponent, ToolComponent, TerminationComponent]--ReturnType = Literal["object", "dict", "config"]--DEFAULT_SELECTOR_PROMPT = """You are in a role play game. The following roles are available:-{roles}.-Read the following conversation. Then select the next role from {participants} to play. Only return the role.--{history}--Read the above conversation. Then select the next role from {participants} to play. Only return the role.-"""--CONFIG_RETURN_TYPES = Literal["object", "dict", "config"]---class ComponentFactory:- """Creates and manages agent components with versioned configuration loading"""-- SUPPORTED_VERSIONS = {- ComponentTypes.TEAM: ["1.0.0"],- ComponentTypes.AGENT: ["1.0.0"],- ComponentTypes.MODEL: ["1.0.0"],- ComponentTypes.TOOL: ["1.0.0"],- ComponentTypes.TERMINATION: ["1.0.0"],- }-- def __init__(self):- self._model_cache: Dict[str, ModelComponent] = {}- self._tool_cache: Dict[str, FunctionTool] = {}- self._last_cache_clear = datetime.now()-- async def load(- self, component: ComponentConfigInput, input_func: Optional[Callable] = None, return_type: ReturnType = "object"- ) -> Union[Component, dict, ComponentConfig]:- """- Universal loader for any component type-- Args:- component: Component configuration (file path, dict, or ComponentConfig)- input_func: Optional callable for user input handling- return_type: Type of return value ('object', 'dict', or 'config')-- Returns:- Component instance, config dict, or ComponentConfig based on return_type- """- try:- # Load and validate config- if isinstance(component, (str, Path)):- component_dict = await self._load_from_file(component)- config = self._dict_to_config(component_dict)- elif isinstance(component, dict):- config = self._dict_to_config(component)- else:- config = component-- # Validate version- if not self._is_version_supported(config.component_type, config.version):- raise ValueError(- f"Unsupported version {config.version} for "- f"component type {config.component_type}. "- f"Supported versions: {self.SUPPORTED_VERSIONS[config.component_type]}"- )-- # Return early if dict or config requested- if return_type == "dict":- return config.model_dump()- elif return_type == "config":- return config-- # Otherwise create and return component instance- handlers = {- ComponentTypes.TEAM: lambda c: self.load_team(c, input_func),- ComponentTypes.AGENT: lambda c: self.load_agent(c, input_func),- ComponentTypes.MODEL: self.load_model,- ComponentTypes.TOOL: self.load_tool,- ComponentTypes.TERMINATION: self.load_termination,- }-- handler = handlers.get(config.component_type)- if not handler:- raise ValueError(f"Unknown component type: {config.component_type}")-- return await handler(config)-- except Exception as e:- logger.error(f"Failed to load component: {str(e)}")- raise-- async def load_directory(- self, directory: Union[str, Path], return_type: ReturnType = "object"- ) -> List[Union[Component, dict, ComponentConfig]]:- """- Import all component configurations from a directory.- """- components = []- try:- directory = Path(directory)- # Using Path.iterdir() instead of os.listdir- for path in list(directory.glob("*")):- if path.suffix.lower().endswith((".json", ".yaml", ".yml")):- try:- component = await self.load(path, return_type=return_type)- components.append(component)- except Exception as e:- logger.info(f"Failed to load component: {str(e)}, {path}")-- return components- except Exception as e:- logger.info(f"Failed to load directory: {str(e)}")- return components-- def _dict_to_config(self, config_dict: dict) -> ComponentConfig:- """Convert dictionary to appropriate config type based on component_type and type discriminator"""- if "component_type" not in config_dict:- raise ValueError("component_type is required in configuration")-- component_type = ComponentTypes(config_dict["component_type"])-- # Define mapping structure- type_mappings = {- ComponentTypes.MODEL: {- "discriminator": "model_type",- ModelTypes.OPENAI.value: OpenAIModelConfig,- ModelTypes.AZUREOPENAI.value: AzureOpenAIModelConfig,- },- ComponentTypes.AGENT: {- "discriminator": "agent_type",- AgentTypes.ASSISTANT.value: AssistantAgentConfig,- AgentTypes.USERPROXY.value: UserProxyAgentConfig,- AgentTypes.MULTIMODAL_WEBSURFER.value: MultimodalWebSurferAgentConfig,- },- ComponentTypes.TEAM: {- "discriminator": "team_type",- TeamTypes.ROUND_ROBIN.value: RoundRobinTeamConfig,- TeamTypes.SELECTOR.value: SelectorTeamConfig,- TeamTypes.MAGENTIC_ONE.value: MagenticOneTeamConfig,- },- ComponentTypes.TOOL: ToolConfig,- ComponentTypes.TERMINATION: {- "discriminator": "termination_type",- TerminationTypes.MAX_MESSAGES.value: MaxMessageTerminationConfig,- TerminationTypes.TEXT_MENTION.value: TextMentionTerminationConfig,- TerminationTypes.COMBINATION.value: CombinationTerminationConfig,- },- }-- mapping = type_mappings.get(component_type)- if not mapping:- raise ValueError(f"Unknown component type: {component_type}")-- # Handle simple cases (no discriminator)- if isinstance(mapping, type):- return mapping(**config_dict)-- # Get discriminator field value- discriminator = mapping["discriminator"]- if discriminator not in config_dict:- raise ValueError(f"Missing {discriminator} in configuration")-- type_value = config_dict[discriminator]- config_class = mapping.get(type_value)-- if not config_class:- raise ValueError(f"Unknown {discriminator}: {type_value}")-- return config_class(**config_dict)-- async def load_termination(self, config: TerminationConfig) -> TerminationComponent:- """Create termination condition instance from configuration."""- try:- if config.termination_type == TerminationTypes.COMBINATION:- if not config.conditions or len(config.conditions) < 2:- raise ValueError("Combination termination requires at least 2 conditions")- if not config.operator:- raise ValueError("Combination termination requires an operator (and/or)")-- # Load first two conditions- conditions = [await self.load_termination(cond) for cond in config.conditions[:2]]- result = conditions[0] & conditions[1] if config.operator == "and" else conditions[0] | conditions[1]-- # Process remaining conditions if any- for condition in config.conditions[2:]:- next_condition = await self.load_termination(condition)- result = result & next_condition if config.operator == "and" else result | next_condition-- return result-- elif config.termination_type == TerminationTypes.MAX_MESSAGES:- if config.max_messages is None:- raise ValueError("max_messages parameter required for MaxMessageTermination")- return MaxMessageTermination(max_messages=config.max_messages)-- elif config.termination_type == TerminationTypes.STOP_MESSAGE:- return StopMessageTermination()-- elif config.termination_type == TerminationTypes.TEXT_MENTION:- if not config.text:- raise ValueError("text parameter required for TextMentionTermination")- return TextMentionTermination(text=config.text)-- else:- raise ValueError(f"Unsupported termination type: {config.termination_type}")-- except Exception as e:- logger.error(f"Failed to create termination condition: {str(e)}")- raise ValueError(f"Termination condition creation failed: {str(e)}") from e-- async def load_team(self, config: TeamConfig, input_func: Optional[Callable] = None) -> TeamComponent:- """Create team instance from configuration."""- try:- # Load participants (agents) with input_func- participants = []- for participant in config.participants:- agent = await self.load(participant, input_func=input_func)- participants.append(agent)-- # Load termination condition if specified- termination = None- if config.termination_condition:- termination = await self.load(config.termination_condition)-- # Create team based on type- if config.team_type == TeamTypes.ROUND_ROBIN:- return RoundRobinGroupChat(participants=participants, termination_condition=termination)- elif config.team_type == TeamTypes.SELECTOR:- model_client = await self.load(config.model_client)- if not model_client:- raise ValueError("SelectorGroupChat requires a model_client")- selector_prompt = config.selector_prompt if config.selector_prompt else DEFAULT_SELECTOR_PROMPT- return SelectorGroupChat(- participants=participants,- model_client=model_client,- termination_condition=termination,- selector_prompt=selector_prompt,- )- elif config.team_type == TeamTypes.MAGENTIC_ONE:- model_client = await self.load(config.model_client)- if not model_client:- raise ValueError("MagenticOneGroupChat requires a model_client")- return MagenticOneGroupChat(- participants=participants,- model_client=model_client,- termination_condition=termination if termination is not None else None,- max_turns=config.max_turns if config.max_turns is not None else 20,- )- else:- raise ValueError(f"Unsupported team type: {config.team_type}")-- except Exception as e:- logger.error(f"Failed to create team {config.name}: {str(e)}")- raise ValueError(f"Team creation failed: {str(e)}") from e-- async def load_agent(self, config: AgentConfig, input_func: Optional[Callable] = None) -> AgentComponent:- """Create agent instance from configuration."""-- model_client = None- system_message = None- tools = []- if hasattr(config, "system_message") and config.system_message:- system_message = config.system_message- if hasattr(config, "model_client") and config.model_client:- model_client = await self.load(config.model_client)- if hasattr(config, "tools") and config.tools:- for tool_config in config.tools:- tool = await self.load(tool_config)- tools.append(tool)-- try:- if config.agent_type == AgentTypes.USERPROXY:- return UserProxyAgent(- name=config.name,- description=config.description or "A human user",- input_func=input_func, # Pass through to UserProxyAgent- )- elif config.agent_type == AgentTypes.ASSISTANT:- system_message = config.system_message if config.system_message else "You are a helpful assistant"-- return AssistantAgent(- name=config.name,- description=config.description or "A helpful assistant",- model_client=model_client,- tools=tools,- system_message=system_message,- )- elif config.agent_type == AgentTypes.MULTIMODAL_WEBSURFER:- return MultimodalWebSurfer(- name=config.name,- model_client=model_client,- headless=config.headless if config.headless is not None else True,- debug_dir=config.logs_dir if config.logs_dir is not None else None,- downloads_folder=config.logs_dir if config.logs_dir is not None else None,- to_save_screenshots=config.to_save_screenshots if config.to_save_screenshots is not None else False,- use_ocr=config.use_ocr if config.use_ocr is not None else False,- animate_actions=config.animate_actions if config.animate_actions is not None else False,- )- elif config.agent_type == AgentTypes.FILE_SURFER:- return FileSurfer(- name=config.name,- model_client=model_client,- )- elif config.agent_type == AgentTypes.MAGENTIC_ONE_CODER:- return MagenticOneCoderAgent(- name=config.name,- model_client=model_client,- )- else:- raise ValueError(f"Unsupported agent type: {config.agent_type}")-- except Exception as e:- logger.error(f"Failed to create agent {config.name}: {str(e)}")- raise ValueError(f"Agent creation failed: {str(e)}") from e-- async def load_model(self, config: ModelConfig) -> ModelComponent:- """Create model instance from configuration."""- try:- # Check cache first- cache_key = str(config.model_dump())- if cache_key in self._model_cache:- logger.debug(f"Using cached model for {config.model}")- return self._model_cache[cache_key]-- if config.model_type == ModelTypes.OPENAI:- args = {- "model": config.model,- "api_key": config.api_key,- "base_url": config.base_url,- }-- if hasattr(config, "model_capabilities") and config.model_capabilities is not None:- args["model_capabilities"] = config.model_capabilities-- model = OpenAIChatCompletionClient(**args)- self._model_cache[cache_key] = model- return model- elif config.model_type == ModelTypes.AZUREOPENAI:- model = AzureOpenAIChatCompletionClient(- azure_deployment=config.azure_deployment,- model=config.model,- api_version=config.api_version,- azure_endpoint=config.azure_endpoint,- api_key=config.api_key,- )- self._model_cache[cache_key] = model- return model- else:- raise ValueError(f"Unsupported model type: {config.model_type}")-- except Exception as e:- logger.error(f"Failed to create model {config.model}: {str(e)}")- raise ValueError(f"Model creation failed: {str(e)}") from e-- async def load_tool(self, config: ToolConfig) -> ToolComponent:- """Create tool instance from configuration."""- try:- # Validate required fields- if not all([config.name, config.description, config.content, config.tool_type]):- raise ValueError("Tool configuration missing required fields")-- # Check cache first- cache_key = str(config.model_dump())- if cache_key in self._tool_cache:- logger.debug(f"Using cached tool '{config.name}'")- return self._tool_cache[cache_key]-- if config.tool_type == ToolTypes.PYTHON_FUNCTION:- tool = FunctionTool(- name=config.name, description=config.description, func=self._func_from_string(config.content)- )- self._tool_cache[cache_key] = tool- return tool- else:- raise ValueError(f"Unsupported tool type: {config.tool_type}")-- except Exception as e:- logger.error(f"Failed to create tool '{config.name}': {str(e)}")- raise-- async def _load_from_file(self, path: Union[str, Path]) -> dict:- """Load configuration from JSON or YAML file."""- path = Path(path)- if not path.exists():- raise FileNotFoundError(f"Config file not found: {path}")-- try:- async with aiofiles.open(path) as f:- content = await f.read()- if path.suffix == ".json":- return json.loads(content)- elif path.suffix in (".yml", ".yaml"):- return yaml.safe_load(content)- else:- raise ValueError(f"Unsupported file format: {path.suffix}")- except Exception as e:- raise ValueError(f"Failed to load file {path}: {str(e)}") from e-- def _func_from_string(self, content: str) -> callable:- """Convert function string to callable."""- try:- namespace = {}- exec(content, namespace)- for item in namespace.values():- if callable(item) and not isinstance(item, type):- return item- raise ValueError("No function found in provided code")- except Exception as e:- raise ValueError(f"Failed to create function: {str(e)}") from e-- def _is_version_supported(self, component_type: ComponentTypes, ver: str) -> bool:- """Check if version is supported for component type."""- try:- version = Version(ver)- supported = [Version(v) for v in self.SUPPORTED_VERSIONS[component_type]]- return any(version == v for v in supported)- except ValueError:- return False-- async def cleanup(self) -> None:- """Cleanup resources and clear caches."""- for model in self._model_cache.values():- if hasattr(model, "cleanup"):- await model.cleanup()-- for tool in self._tool_cache.values():- if hasattr(tool, "cleanup"):- await tool.cleanup()-- self._model_cache.clear()- self._tool_cache.clear()- self._last_cache_clear = datetime.now()- logger.info("Cleared all component caches")diff --git a/python/packages/autogen-studio/autogenstudio/database/config_manager.py b/python/packages/autogen-studio/autogenstudio/database/config_manager.pydeleted file mode 100644index 3cd1b43d8..000000000--- a/python/packages/autogen-studio/autogenstudio/database/config_manager.py+++ /dev/null@@ -1,268 +0,0 @@-import logging-from pathlib import Path-from typing import Any, Dict, List, Optional, Union--from loguru import logger--from ..datamodel.db import Agent, LinkTypes, Model, Team, Tool-from ..datamodel.types import ComponentConfigInput, ComponentTypes, Response-from .component_factory import ComponentFactory-from .db_manager import DatabaseManager---class ConfigurationManager:- """Manages persistence and relationships of components using ComponentFactory for validation"""-- DEFAULT_UNIQUENESS_FIELDS = {- ComponentTypes.MODEL: ["model_type", "model"],- ComponentTypes.TOOL: ["name"],- ComponentTypes.AGENT: ["agent_type", "name"],- ComponentTypes.TEAM: ["team_type", "name"],- }-- def __init__(self, db_manager: DatabaseManager, uniqueness_fields: Dict[ComponentTypes, List[str]] = None):- self.db_manager = db_manager- self.component_factory = ComponentFactory()- self.uniqueness_fields = uniqueness_fields or self.DEFAULT_UNIQUENESS_FIELDS-- async def import_component(- self, component_config: ComponentConfigInput, user_id: str, check_exists: bool = False- ) -> Response:- """- Import a component configuration, validate it, and store the resulting component.-- Args:- component_config: Configuration for the component (file path, dict, or ComponentConfig)- user_id: User ID to associate with imported component- check_exists: Whether to check for existing components before storing (default: False)-- Returns:- Response containing import results or error- """- try:- # Get validated config as dict- config = await self.component_factory.load(component_config, return_type="dict")-- # Get component type- component_type = self._determine_component_type(config)- if not component_type:- raise ValueError("Unable to determine component type from config")-- # Check existence if requested- if check_exists:- existing = self._check_exists(component_type, config, user_id)- if existing:- return Response(- message=self._format_exists_message(component_type, config),- status=True,- data={"id": existing.id},- )-- # Route to appropriate storage method- if component_type == ComponentTypes.TEAM:- return await self._store_team(config, user_id, check_exists)- elif component_type == ComponentTypes.AGENT:- return await self._store_agent(config, user_id, check_exists)- elif component_type == ComponentTypes.MODEL:- return await self._store_model(config, user_id)- elif component_type == ComponentTypes.TOOL:- return await self._store_tool(config, user_id)- else:- raise ValueError(f"Unsupported component type: {component_type}")-- except Exception as e:- logger.error(f"Failed to import component: {str(e)}")- return Response(message=str(e), status=False)-- async def import_directory(self, directory: Union[str, Path], user_id: str, check_exists: bool = False) -> Response:- """- Import all component configurations from a directory.-- Args:- directory: Path to directory containing configuration files- user_id: User ID to associate with imported components- check_exists: Whether to check for existing components before storing (default: False)-- Returns:- Response containing import results for all files- """- try:- configs = await self.component_factory.load_directory(directory, return_type="dict")-- results = []- for config in configs:- result = await self.import_component(config, user_id, check_exists)- results.append(- {- "component": self._get_component_type(config),- "status": result.status,- "message": result.message,- "id": result.data.get("id") if result.status else None,- }- )-- return Response(message="Directory import complete", status=True, data=results)-- except Exception as e:- logger.error(f"Failed to import directory: {str(e)}")- return Response(message=str(e), status=False)-- async def _store_team(self, config: dict, user_id: str, check_exists: bool = False) -> Response:- """Store team component and manage its relationships with agents"""- try:- # Store the team- team_db = Team(user_id=user_id, config=config)- team_result = self.db_manager.upsert(team_db)- if not team_result.status:- return team_result-- team_id = team_result.data["id"]-- # Handle participants (agents)- for participant in config.get("participants", []):- if check_exists:- # Check for existing agent- agent_type = self._determine_component_type(participant)- existing_agent = self._check_exists(agent_type, participant, user_id)- if existing_agent:- # Link existing agent- self.db_manager.link(LinkTypes.TEAM_AGENT, team_id, existing_agent.id)- logger.info(f"Linked existing agent to team: {existing_agent}")- continue-- # Store and link new agent- agent_result = await self._store_agent(participant, user_id, check_exists)- if agent_result.status:- self.db_manager.link(LinkTypes.TEAM_AGENT, team_id, agent_result.data["id"])-- return team_result-- except Exception as e:- logger.error(f"Failed to store team: {str(e)}")- return Response(message=str(e), status=False)-- async def _store_agent(self, config: dict, user_id: str, check_exists: bool = False) -> Response:- """Store agent component and manage its relationships with tools and model"""- try:- # Store the agent- agent_db = Agent(user_id=user_id, config=config)- agent_result = self.db_manager.upsert(agent_db)- if not agent_result.status:- return agent_result-- agent_id = agent_result.data["id"]-- # Handle model client- if "model_client" in config:- if check_exists:- # Check for existing model- model_type = self._determine_component_type(config["model_client"])- existing_model = self._check_exists(model_type, config["model_client"], user_id)- if existing_model:- # Link existing model- self.db_manager.link(LinkTypes.AGENT_MODEL, agent_id, existing_model.id)- logger.info(f"Linked existing model to agent: {existing_model.config.model_type}")- else:- # Store and link new model- model_result = await self._store_model(config["model_client"], user_id)- if model_result.status:- self.db_manager.link(LinkTypes.AGENT_MODEL, agent_id, model_result.data["id"])- else:- # Store and link new model without checking- model_result = await self._store_model(config["model_client"], user_id)- if model_result.status:- self.db_manager.link(LinkTypes.AGENT_MODEL, agent_id, model_result.data["id"])-- # Handle tools- for tool_config in config.get("tools", []):- if check_exists:- # Check for existing tool- tool_type = self._determine_component_type(tool_config)- existing_tool = self._check_exists(tool_type, tool_config, user_id)- if existing_tool:- # Link existing tool- self.db_manager.link(LinkTypes.AGENT_TOOL, agent_id, existing_tool.id)- logger.info(f"Linked existing tool to agent: {existing_tool.config.name}")- continue-- # Store and link new tool- tool_result = await self._store_tool(tool_config, user_id)- if tool_result.status:- self.db_manager.link(LinkTypes.AGENT_TOOL, agent_id, tool_result.data["id"])-- return agent_result-- except Exception as e:- logger.error(f"Failed to store agent: {str(e)}")- return Response(message=str(e), status=False)-- async def _store_model(self, config: dict, user_id: str) -> Response:- """Store model component (leaf node - no relationships)"""- try:- model_db = Model(user_id=user_id, config=config)- return self.db_manager.upsert(model_db)-- except Exception as e:- logger.error(f"Failed to store model: {str(e)}")- return Response(message=str(e), status=False)-- async def _store_tool(self, config: dict, user_id: str) -> Response:- """Store tool component (leaf node - no relationships)"""- try:- tool_db = Tool(user_id=user_id, config=config)- return self.db_manager.upsert(tool_db)-- except Exception as e:- logger.error(f"Failed to store tool: {str(e)}")- return Response(message=str(e), status=False)-- def _check_exists(- self, component_type: ComponentTypes, config: dict, user_id: str- ) -> Optional[Union[Model, Tool, Agent, Team]]:- """Check if component exists based on configured uniqueness fields."""- fields = self.uniqueness_fields.get(component_type, [])- if not fields:- return None-- component_class = {- ComponentTypes.MODEL: Model,- ComponentTypes.TOOL: Tool,- ComponentTypes.AGENT: Agent,- ComponentTypes.TEAM: Team,- }.get(component_type)-- components = self.db_manager.get(component_class, {"user_id": user_id}).data-- for component in components:- matches = all(component.config.get(field) == config.get(field) for field in fields)- if matches:- return component-- return None-- def _format_exists_message(self, component_type: ComponentTypes, config: dict) -> str:- """Format existence message with identifying fields."""- fields = self.uniqueness_fields.get(component_type, [])- field_values = [f"{field}='{config.get(field)}'" for field in fields]- return f"{component_type.value} with {' and '.join(field_values)} already exists"-- def _determine_component_type(self, config: dict) -> Optional[ComponentTypes]:- """Determine component type from configuration dictionary"""- if "team_type" in config:- return ComponentTypes.TEAM- elif "agent_type" in config:- return ComponentTypes.AGENT- elif "model_type" in config:- return ComponentTypes.MODEL- elif "tool_type" in config:- return ComponentTypes.TOOL- return None-- def _get_component_type(self, config: dict) -> str:- """Helper to get component type string from config"""- component_type = self._determine_component_type(config)- return component_type.value if component_type else "unknown"-- async def cleanup(self):- """Cleanup resources"""- await self.component_factory.cleanup()diff --git a/python/packages/autogen-studio/autogenstudio/database/db_manager.py b/python/packages/autogen-studio/autogenstudio/database/db_manager.pyindex 2b9ec43e3..1df428016 100644--- a/python/packages/autogen-studio/autogenstudio/database/db_manager.py+++ b/python/packages/autogen-studio/autogenstudio/database/db_manager.py@@ -1,17 +1,16 @@import threadingfrom datetime import datetimefrom pathlib import Path-from typing import Optional+from typing import Optional, Unionfrom loguru import logger-from sqlalchemy import exc, func, inspect, text+from sqlalchemy import exc, inspect, textfrom sqlmodel import Session, SQLModel, and_, create_engine, select-from ..datamodel import LinkTypes, Response+from ..datamodel import Response, Team+from ..teammanager import TeamManagerfrom .schema_manager import SchemaManager-# from .dbutils import init_db_samples-class DatabaseManager:_init_lock = threading.Lock()@@ -247,152 +246,85 @@ class DatabaseManager:return Response(message=status_message, status=status, data=None)- def link(- self,- link_type: LinkTypes,- primary_id: int,- secondary_id: int,- sequence: Optional[int] = None,- ):- """Link two entities with automatic sequence handling."""- with Session(self.engine) as session:- try:- # Get classes from LinkTypes- primary_class = link_type.primary_class- secondary_class = link_type.secondary_class- link_table = link_type.link_table-- # Get entities- primary_entity = session.get(primary_class, primary_id)- secondary_entity = session.get(secondary_class, secondary_id)-- if not primary_entity or not secondary_entity:- return Response(message="One or both entities do not exist", status=False)-- # Get field names- primary_id_field = f"{primary_class.__name__.lower()}_id"- secondary_id_field = f"{secondary_class.__name__.lower()}_id"-- # Check for existing link- existing_link = session.exec(- select(link_table).where(- and_(- getattr(link_table, primary_id_field) == primary_id,- getattr(link_table, secondary_id_field) == secondary_id,- )- )- ).first()-- if existing_link:- return Response(message="Link already exists", status=False)-- # Get the next sequence number if not provided- if sequence is None:- max_seq_result = session.exec(- select(func.max(link_table.sequence)).where(getattr(link_table, primary_id_field) == primary_id)- ).first()- sequence = 0 if max_seq_result is None else max_seq_result + 1-- # Create new link- new_link = link_table(- **{primary_id_field: primary_id, secondary_id_field: secondary_id, "sequence": sequence}- )- session.add(new_link)- session.commit()-- return Response(message=f"Entities linked successfully with sequence {sequence}", status=True)-- except Exception as e:- session.rollback()- return Response(message=f"Error linking entities: {str(e)}", status=False)-- def unlink(self, link_type: LinkTypes, primary_id: int, secondary_id: int, sequence: Optional[int] = None):- """Unlink two entities and reorder sequences if needed."""- with Session(self.engine) as session:- try:- # Get classes from LinkTypes- primary_class = link_type.primary_class- secondary_class = link_type.secondary_class- link_table = link_type.link_table-- # Get field names- primary_id_field = f"{primary_class.__name__.lower()}_id"- secondary_id_field = f"{secondary_class.__name__.lower()}_id"-- # Find existing link- statement = select(link_table).where(- and_(- getattr(link_table, primary_id_field) == primary_id,- getattr(link_table, secondary_id_field) == secondary_id,+ async def import_team(+ self, team_config: Union[str, Path, dict], user_id: str, check_exists: bool = False+ ) -> Response:+ try:+ # Load config if path provided+ if isinstance(team_config, (str, Path)):+ config = await TeamManager.load_from_file(team_config)+ else:+ config = team_config++ # Check existence if requested+ if check_exists:+ existing = await self._check_team_exists(config, user_id)+ if existing:+ return Response(+ message="Identical team configuration already exists", status=True, data={"id": existing.id})- )- if sequence is not None:- statement = statement.where(link_table.sequence == sequence)+ # Store in database+ team_db = Team(user_id=user_id, config=config)- existing_link = session.exec(statement).first()+ result = self.upsert(team_db)+ return result- if not existing_link:- return Response(message="Link does not exist", status=False)-- deleted_sequence = existing_link.sequence- session.delete(existing_link)-- # Reorder sequences for remaining links- remaining_links = session.exec(- select(link_table)- .where(getattr(link_table, primary_id_field) == primary_id)- .where(link_table.sequence > deleted_sequence)- .order_by(link_table.sequence)- ).all()-- # Decrease sequence numbers to fill the gap- for link in remaining_links:- link.sequence -= 1+ except Exception as e:+ logger.error(f"Failed to import team: {str(e)}")+ return Response(message=str(e), status=False)- session.commit()+ async def import_teams_from_directory(+ self, directory: Union[str, Path], user_id: str, check_exists: bool = False+ ) -> Response:+ """+ Import all team configurations from a directory.- return Response(message="Entities unlinked successfully and sequences reordered", status=True)+ Args:+ directory: Path to directory containing team configs+ user_id: User ID to associate with imported teams+ check_exists: Whether to check for existing teams- except Exception as e:- session.rollback()- return Response(message=f"Error unlinking entities: {str(e)}", status=False)+ Returns:+ Response containing import results for all files+ """+ try:+ # Load all configs from directory+ configs = await TeamManager.load_from_directory(directory)- def get_linked_entities(- self,- link_type: LinkTypes,- primary_id: int,- return_json: bool = False,- ):- """Get linked entities based on link type and primary ID, ordered by sequence."""- with Session(self.engine) as session:- try:- # Get classes from LinkTypes- primary_class = link_type.primary_class- secondary_class = link_type.secondary_class- link_table = link_type.link_table+ results = []+ for config in configs:+ try:+ result = await self.import_team(team_config=config, user_id=user_id, check_exists=check_exists)++ # Add result info+ results.append(+ {+ "status": result.status,+ "message": result.message,+ "id": result.data.get("id") if result.status else None,+ }+ )- # Get field names- primary_id_field = f"{primary_class.__name__.lower()}_id"- secondary_id_field = f"{secondary_class.__name__.lower()}_id"+ except Exception as e:+ logger.error(f"Failed to import team config: {str(e)}")+ results.append({"status": False, "message": str(e), "id": None})- # Query both link and entity, ordered by sequence- items = session.exec(- select(secondary_class)- .join(link_table, getattr(link_table, secondary_id_field) == secondary_class.id)- .where(getattr(link_table, primary_id_field) == primary_id)- .order_by(link_table.sequence)- ).all()+ return Response(message="Directory import complete", status=True, data=results)- result = [item.model_dump() if return_json else item for item in items]+ except Exception as e:+ logger.error(f"Failed to import directory: {str(e)}")+ return Response(message=str(e), status=False)- return Response(message="Linked entities retrieved successfully", status=True, data=result)+ async def _check_team_exists(self, config: dict, user_id: str) -> Optional[Team]:+ """Check if identical team config already exists"""+ teams = self.get(Team, {"user_id": user_id}).data- except Exception as e:- logger.error(f"Error getting linked entities: {str(e)}")- return Response(message=f"Error getting linked entities: {str(e)}", status=False, data=[])+ for team in teams:+ if team.config == config:+ return team- # Add new close method+ return Noneasync def close(self):"""Close database connections and cleanup resources"""diff --git a/python/packages/autogen-studio/autogenstudio/database/gallery_builder.py b/python/packages/autogen-studio/autogenstudio/database/gallery_builder.pynew file mode 100644index 000000000..7b4d69ab4--- /dev/null+++ b/python/packages/autogen-studio/autogenstudio/database/gallery_builder.py@@ -0,0 +1,243 @@+from datetime import datetime+from typing import List, Optional++from autogen_agentchat.agents import AssistantAgent, UserProxyAgent+from autogen_agentchat.conditions import MaxMessageTermination, TextMentionTermination+from autogen_agentchat.teams import RoundRobinGroupChat, SelectorGroupChat+from autogen_core import ComponentModel+from autogen_core.models import ModelInfo+from autogen_core.tools import FunctionTool+from autogen_ext.agents.web_surfer import MultimodalWebSurfer+from autogen_ext.models.openai import OpenAIChatCompletionClient++from autogenstudio.datamodel import Gallery, GalleryComponents, GalleryItems, GalleryMetadata+++class GalleryBuilder:+ """Builder class for creating AutoGen component galleries."""++ def __init__(self, id: str, name: str):+ self.id = id+ self.name = name+ self.url: Optional[str] = None+ self.teams: List[ComponentModel] = []+ self.agents: List[ComponentModel] = []+ self.models: List[ComponentModel] = []+ self.tools: List[ComponentModel] = []+ self.terminations: List[ComponentModel] = []++ # Default metadata+ self.metadata = GalleryMetadata(+ author="AutoGen Team",+ created_at=datetime.now(),+ updated_at=datetime.now(),+ version="1.0.0",+ description="",+ tags=[],+ license="MIT",+ category="conversation",+ )++ def set_metadata(+ self,+ author: Optional[str] = None,+ version: Optional[str] = None,+ description: Optional[str] = None,+ tags: Optional[List[str]] = None,+ license: Optional[str] = None,+ category: Optional[str] = None,+ ) -> "GalleryBuilder":+ """Update gallery metadata."""+ if author:+ self.metadata.author = author+ if version:+ self.metadata.version = version+ if description:+ self.metadata.description = description+ if tags:+ self.metadata.tags = tags+ if license:+ self.metadata.license = license+ if category:+ self.metadata.category = category+ return self++ def add_team(self, team: ComponentModel) -> "GalleryBuilder":+ """Add a team component to the gallery."""+ self.teams.append(team)+ return self++ def add_agent(self, agent: ComponentModel) -> "GalleryBuilder":+ """Add an agent component to the gallery."""+ self.agents.append(agent)+ return self++ def add_model(self, model: ComponentModel) -> "GalleryBuilder":+ """Add a model component to the gallery."""+ self.models.append(model)+ return self++ def add_tool(self, tool: ComponentModel) -> "GalleryBuilder":+ """Add a tool component to the gallery."""+ self.tools.append(tool)+ return self++ def add_termination(self, termination: ComponentModel) -> "GalleryBuilder":+ """Add a termination condition component to the gallery."""+ self.terminations.append(termination)+ return self++ def build(self) -> Gallery:+ """Build and return the complete gallery."""+ # Update timestamps+ self.metadata.updated_at = datetime.now()++ return Gallery(+ id=self.id,+ name=self.name,+ url=self.url,+ metadata=self.metadata,+ items=GalleryItems(+ teams=self.teams,+ components=GalleryComponents(+ agents=self.agents, models=self.models, tools=self.tools, terminations=self.terminations+ ),+ ),+ )+++def create_default_gallery() -> Gallery:+ """Create a default gallery with all components including calculator and web surfer teams."""+ builder = GalleryBuilder(id="gallery_default", name="Default Component Gallery")++ # Set metadata+ builder.set_metadata(+ description="A default gallery containing basic components for human-in-loop conversations",+ tags=["human-in-loop", "assistant"],+ category="conversation",+ )++ # Create base model client+ base_model = OpenAIChatCompletionClient(model="gpt-4o-mini")+ builder.add_model(base_model.dump_component())++ mistral_vllm_model = OpenAIChatCompletionClient(+ model="TheBloke/Mistral-7B-Instruct-v0.2-GGUF",+ base_url="http://localhost:1234/v1",+ model_info=ModelInfo(vision=False, function_calling=True, json_output=False),+ )+ builder.add_model(mistral_vllm_model.dump_component())++ # Create websurfer model client+ websurfer_model = OpenAIChatCompletionClient(model="gpt-4o-mini")+ builder.add_model(websurfer_model.dump_component())++ def calculator(a: float, b: float, operator: str) -> str:+ try:+ if operator == "+":+ return str(a + b)+ elif operator == "-":+ return str(a - b)+ elif operator == "*":+ return str(a * b)+ elif operator == "/":+ if b == 0:+ return "Error: Division by zero"+ return str(a / b)+ else:+ return "Error: Invalid operator. Please use +, -, *, or /"+ except Exception as e:+ return f"Error: {str(e)}"++ # Create calculator tool+ calculator_tool = FunctionTool(+ name="calculator",+ description="A simple calculator that performs basic arithmetic operations",+ func=calculator,+ global_imports=[],+ )+ builder.add_tool(calculator_tool.dump_component())++ # Create termination conditions for calculator team+ calc_text_term = TextMentionTermination(text="TERMINATE")+ calc_max_term = MaxMessageTermination(max_messages=10)+ calc_or_term = calc_text_term | calc_max_term++ builder.add_termination(calc_text_term.dump_component())+ builder.add_termination(calc_max_term.dump_component())+ builder.add_termination(calc_or_term.dump_component())++ # Create calculator assistant agent+ calc_assistant = AssistantAgent(+ name="assistant_agent",+ system_message="You are a helpful assistant. Solve tasks carefully. When done, say TERMINATE.",+ model_client=base_model,+ tools=[calculator_tool],+ )+ builder.add_agent(calc_assistant.dump_component())++ # Create calculator team+ calc_team = RoundRobinGroupChat(participants=[calc_assistant], termination_condition=calc_or_term)+ builder.add_team(calc_team.dump_component())++ # Create web surfer agent+ websurfer_agent = MultimodalWebSurfer(+ name="websurfer_agent",+ description="an agent that solves tasks by browsing the web",+ model_client=websurfer_model,+ headless=True,+ )+ builder.add_agent(websurfer_agent.dump_component())++ # Create web surfer verification assistant+ verification_assistant = AssistantAgent(+ name="assistant_agent",+ description="an agent that verifies and summarizes information",+ system_message="You are a task verification assistant who is working with a web surfer agent to solve tasks. At each point, check if the task has been completed as requested by the user. If the websurfer_agent responds and the task has not yet been completed, respond with what is left to do and then say 'keep going'. If and only when the task has been completed, summarize and present a final answer that directly addresses the user task in detail and then respond with TERMINATE.",+ model_client=websurfer_model,+ )+ builder.add_agent(verification_assistant.dump_component())++ # Create web surfer user proxy+ web_user_proxy = UserProxyAgent(+ name="user_proxy",+ description="a human user that should be consulted only when the assistant_agent is unable to verify the information provided by the websurfer_agent",+ )+ builder.add_agent(web_user_proxy.dump_component())++ # Create web surfer team termination conditions+ web_max_term = MaxMessageTermination(max_messages=20)+ web_text_term = TextMentionTermination(text="TERMINATE")+ web_termination = web_max_term | web_text_term+ builder.add_termination(web_termination.dump_component())++ # Create web surfer team+ selector_prompt = """You are the cordinator of role play game. The following roles are available:+{roles}. Given a task, the websurfer_agent will be tasked to address it by browsing the web and providing information. The assistant_agent will be tasked with verifying the information provided by the websurfer_agent and summarizing the information to present a final answer to the user. If the task needs assistance from a human user (e.g., providing feedback, preferences, or the task is stalled), you should select the user_proxy role to provide the necessary information.+Read the following conversation. Then select the next role from {participants} to play. Only return the role.++{history}++Read the above conversation. Then select the next role from {participants} to play. Only return the role."""++ websurfer_team = SelectorGroupChat(+ participants=[websurfer_agent, verification_assistant, web_user_proxy],+ selector_prompt=selector_prompt,+ model_client=base_model,+ termination_condition=web_termination,+ )+ builder.add_team(websurfer_team.dump_component())++ return builder.build()+++# if __name__ == "__main__":+# # Create and save the gallery+# gallery = create_default_gallery()++# # Print as JSON+# print(gallery.model_dump_json(indent=2))++# # Save to file+# with open("gallery_default.json", "w") as f:+# f.write(gallery.model_dump_json(indent=2))diff --git a/python/packages/autogen-studio/autogenstudio/datamodel/__init__.py b/python/packages/autogen-studio/autogenstudio/datamodel/__init__.pyindex 0d46fb263..b47788ed7 100644--- a/python/packages/autogen-studio/autogenstudio/datamodel/__init__.py+++ b/python/packages/autogen-studio/autogenstudio/datamodel/__init__.py@@ -1,11 +1,25 @@-from .db import Agent, LinkTypes, Message, Model, Run, RunStatus, Session, Team, Tool+from .db import Message, Run, RunStatus, Session, Teamfrom .types import (- AgentConfig,- ComponentConfigInput,+ Gallery,+ GalleryComponents,+ GalleryItems,+ GalleryMetadata,MessageConfig,- ModelConfig,+ MessageMeta,Response,- TeamConfig,+ SocketMessage,TeamResult,- ToolConfig,)++__all__ = [+ "Team",+ "Run",+ "RunStatus",+ "Session",+ "Team",+ "MessageConfig",+ "MessageMeta",+ "TeamResult",+ "Response",+ "SocketMessage",+]diff --git a/python/packages/autogen-studio/autogenstudio/datamodel/db.py b/python/packages/autogen-studio/autogenstudio/datamodel/db.pyindex 45f439d33..a568d5b0c 100644--- a/python/packages/autogen-studio/autogenstudio/datamodel/db.py+++ b/python/packages/autogen-studio/autogenstudio/datamodel/db.py@@ -2,141 +2,14 @@from datetime import datetimefrom enum import Enum-from typing import List, Optional, Tuple, Type, Union+from typing import List, Optional, Unionfrom uuid import UUID, uuid4-from loguru import logger-from pydantic import BaseModel-from sqlalchemy import ForeignKey, Integer, UniqueConstraint-from sqlmodel import JSON, Column, DateTime, Field, Relationship, SQLModel, func+from autogen_core import ComponentModel+from sqlalchemy import ForeignKey, Integer+from sqlmodel import JSON, Column, DateTime, Field, SQLModel, func-from .types import AgentConfig, MessageConfig, MessageMeta, ModelConfig, TeamConfig, TeamResult, ToolConfig--# added for python3.11 and sqlmodel 0.0.22 incompatibility-if hasattr(SQLModel, "model_config"):- SQLModel.model_config["protected_namespaces"] = ()-elif hasattr(SQLModel, "Config"):-- class CustomSQLModel(SQLModel):- class Config:- protected_namespaces = ()-- SQLModel = CustomSQLModel-else:- logger.warning("Unable to set protected_namespaces.")--# pylint: disable=protected-access---class ComponentTypes(Enum):- TEAM = "team"- AGENT = "agent"- MODEL = "model"- TOOL = "tool"-- @property- def model_class(self) -> Type[SQLModel]:- return {- ComponentTypes.TEAM: Team,- ComponentTypes.AGENT: Agent,- ComponentTypes.MODEL: Model,- ComponentTypes.TOOL: Tool,- }[self]---class LinkTypes(Enum):- AGENT_MODEL = "agent_model"- AGENT_TOOL = "agent_tool"- TEAM_AGENT = "team_agent"-- @property- # type: ignore- def link_config(self) -> Tuple[Type[SQLModel], Type[SQLModel], Type[SQLModel]]:- return {- LinkTypes.AGENT_MODEL: (Agent, Model, AgentModelLink),- LinkTypes.AGENT_TOOL: (Agent, Tool, AgentToolLink),- LinkTypes.TEAM_AGENT: (Team, Agent, TeamAgentLink),- }[self]-- @property- def primary_class(self) -> Type[SQLModel]: # type: ignore- return self.link_config[0]-- @property- def secondary_class(self) -> Type[SQLModel]: # type: ignore- return self.link_config[1]-- @property- def link_table(self) -> Type[SQLModel]: # type: ignore- return self.link_config[2]---# link models-class AgentToolLink(SQLModel, table=True):- __table_args__ = (- UniqueConstraint("agent_id", "sequence", name="unique_agent_tool_sequence"),- {"sqlite_autoincrement": True},- )- agent_id: int = Field(default=None, primary_key=True, foreign_key="agent.id")- tool_id: int = Field(default=None, primary_key=True, foreign_key="tool.id")- sequence: Optional[int] = Field(default=0, primary_key=True)---class AgentModelLink(SQLModel, table=True):- __table_args__ = (- UniqueConstraint("agent_id", "sequence", name="unique_agent_tool_sequence"),- {"sqlite_autoincrement": True},- )- agent_id: int = Field(default=None, primary_key=True, foreign_key="agent.id")- model_id: int = Field(default=None, primary_key=True, foreign_key="model.id")- sequence: Optional[int] = Field(default=0, primary_key=True)---class TeamAgentLink(SQLModel, table=True):- __table_args__ = (- UniqueConstraint("agent_id", "sequence", name="unique_agent_tool_sequence"),- {"sqlite_autoincrement": True},- )- team_id: int = Field(default=None, primary_key=True, foreign_key="team.id")- agent_id: int = Field(default=None, primary_key=True, foreign_key="agent.id")- sequence: Optional[int] = Field(default=0, primary_key=True)---# database models---class Tool(SQLModel, table=True):- __table_args__ = {"sqlite_autoincrement": True}- id: Optional[int] = Field(default=None, primary_key=True)- created_at: datetime = Field(- default_factory=datetime.now,- sa_column=Column(DateTime(timezone=True), server_default=func.now()),- ) # pylint: disable=not-callable- updated_at: datetime = Field(- default_factory=datetime.now,- sa_column=Column(DateTime(timezone=True), onupdate=func.now()),- ) # pylint: disable=not-callable- user_id: Optional[str] = None- version: Optional[str] = "0.0.1"- config: Union[ToolConfig, dict] = Field(sa_column=Column(JSON))- agents: List["Agent"] = Relationship(back_populates="tools", link_model=AgentToolLink)---class Model(SQLModel, table=True):- __table_args__ = {"sqlite_autoincrement": True}- id: Optional[int] = Field(default=None, primary_key=True)- created_at: datetime = Field(- default_factory=datetime.now,- sa_column=Column(DateTime(timezone=True), server_default=func.now()),- ) # pylint: disable=not-callable- updated_at: datetime = Field(- default_factory=datetime.now,- sa_column=Column(DateTime(timezone=True), onupdate=func.now()),- ) # pylint: disable=not-callable- user_id: Optional[str] = None- version: Optional[str] = "0.0.1"- config: Union[ModelConfig, dict] = Field(sa_column=Column(JSON))- agents: List["Agent"] = Relationship(back_populates="models", link_model=AgentModelLink)+from .types import MessageConfig, MessageMeta, TeamResultclass Team(SQLModel, table=True):@@ -152,27 +25,7 @@ class Team(SQLModel, table=True):) # pylint: disable=not-callableuser_id: Optional[str] = Noneversion: Optional[str] = "0.0.1"- config: Union[TeamConfig, dict] = Field(sa_column=Column(JSON))- agents: List["Agent"] = Relationship(back_populates="teams", link_model=TeamAgentLink)---class Agent(SQLModel, table=True):- __table_args__ = {"sqlite_autoincrement": True}- id: Optional[int] = Field(default=None, primary_key=True)- created_at: datetime = Field(- default_factory=datetime.now,- sa_column=Column(DateTime(timezone=True), server_default=func.now()),- ) # pylint: disable=not-callable- updated_at: datetime = Field(- default_factory=datetime.now,- sa_column=Column(DateTime(timezone=True), onupdate=func.now()),- ) # pylint: disable=not-callable- user_id: Optional[str] = None- version: Optional[str] = "0.0.1"- config: Union[AgentConfig, dict] = Field(sa_column=Column(JSON))- tools: List[Tool] = Relationship(back_populates="agents", link_model=AgentToolLink)- models: List[Model] = Relationship(back_populates="agents", link_model=AgentModelLink)- teams: List[Team] = Relationship(back_populates="agents", link_model=TeamAgentLink)+ component: Union[ComponentModel, dict] = Field(sa_column=Column(JSON))class Message(SQLModel, table=True):@@ -250,32 +103,3 @@ class Run(SQLModel, table=True):class Config:json_encoders = {UUID: str, datetime: lambda v: v.isoformat()}---class GalleryConfig(SQLModel, table=False):- id: UUID = Field(default_factory=uuid4, primary_key=True, index=True)- title: Optional[str] = None- description: Optional[str] = None- run: Run- team: TeamConfig = None- tags: Optional[List[str]] = None- visibility: str = "public" # public, private, shared-- class Config:- json_encoders = {UUID: str, datetime: lambda v: v.isoformat()}---class Gallery(SQLModel, table=True):- __table_args__ = {"sqlite_autoincrement": True}- id: Optional[int] = Field(default=None, primary_key=True)- created_at: datetime = Field(- default_factory=datetime.now,- sa_column=Column(DateTime(timezone=True), server_default=func.now()),- )- updated_at: datetime = Field(- default_factory=datetime.now,- sa_column=Column(DateTime(timezone=True), onupdate=func.now()),- )- user_id: Optional[str] = None- version: Optional[str] = "0.0.1"- config: Union[GalleryConfig, dict] = Field(default_factory=GalleryConfig, sa_column=Column(JSON))diff --git a/python/packages/autogen-studio/autogenstudio/datamodel/types.py b/python/packages/autogen-studio/autogenstudio/datamodel/types.pyindex eb02fb121..b35b7a054 100644--- a/python/packages/autogen-studio/autogenstudio/datamodel/types.py+++ b/python/packages/autogen-studio/autogenstudio/datamodel/types.py@@ -1,55 +1,9 @@from datetime import datetime-from enum import Enum-from pathlib import Path-from typing import Any, Dict, List, Optional, Union+from typing import Any, Dict, List, Optionalfrom autogen_agentchat.base import TaskResult-from autogen_core.models import ModelCapabilities-from pydantic import BaseModel, Field---class ModelTypes(str, Enum):- OPENAI = "OpenAIChatCompletionClient"- AZUREOPENAI = "AzureOpenAIChatCompletionClient"---class ToolTypes(str, Enum):- PYTHON_FUNCTION = "PythonFunction"---class AgentTypes(str, Enum):- ASSISTANT = "AssistantAgent"- USERPROXY = "UserProxyAgent"- MULTIMODAL_WEBSURFER = "MultimodalWebSurfer"- FILE_SURFER = "FileSurfer"- MAGENTIC_ONE_CODER = "MagenticOneCoderAgent"---class TeamTypes(str, Enum):- ROUND_ROBIN = "RoundRobinGroupChat"- SELECTOR = "SelectorGroupChat"- MAGENTIC_ONE = "MagenticOneGroupChat"---class TerminationTypes(str, Enum):- MAX_MESSAGES = "MaxMessageTermination"- STOP_MESSAGE = "StopMessageTermination"- TEXT_MENTION = "TextMentionTermination"- COMBINATION = "CombinationTermination"---class ComponentTypes(str, Enum):- TEAM = "team"- AGENT = "agent"- MODEL = "model"- TOOL = "tool"- TERMINATION = "termination"---class BaseConfig(BaseModel):- model_config = {"protected_namespaces": ()}- version: str = "1.0.0"- component_type: ComponentTypes+from autogen_core import ComponentModel+from pydantic import BaseModelclass MessageConfig(BaseModel):@@ -58,134 +12,6 @@ class MessageConfig(BaseModel):message_type: Optional[str] = "text"-class BaseModelConfig(BaseConfig):- model: str- model_type: ModelTypes- api_key: Optional[str] = None- base_url: Optional[str] = None- component_type: ComponentTypes = ComponentTypes.MODEL- model_capabilities: Optional[ModelCapabilities] = None---class OpenAIModelConfig(BaseModelConfig):- model_type: ModelTypes = ModelTypes.OPENAI---class AzureOpenAIModelConfig(BaseModelConfig):- azure_deployment: str- model: str- api_version: str- azure_endpoint: str- azure_ad_token_provider: Optional[str] = None- api_key: Optional[str] = None- model_type: ModelTypes = ModelTypes.AZUREOPENAI---ModelConfig = OpenAIModelConfig | AzureOpenAIModelConfig---class ToolConfig(BaseConfig):- name: str- description: str- content: str- tool_type: ToolTypes- component_type: ComponentTypes = ComponentTypes.TOOL---class BaseAgentConfig(BaseConfig):- name: str- agent_type: AgentTypes- description: Optional[str] = None- component_type: ComponentTypes = ComponentTypes.AGENT---class AssistantAgentConfig(BaseAgentConfig):- agent_type: AgentTypes = AgentTypes.ASSISTANT- model_client: ModelConfig- tools: Optional[List[ToolConfig]] = None- system_message: Optional[str] = None---class UserProxyAgentConfig(BaseAgentConfig):- agent_type: AgentTypes = AgentTypes.USERPROXY---class MultimodalWebSurferAgentConfig(BaseAgentConfig):- agent_type: AgentTypes = AgentTypes.MULTIMODAL_WEBSURFER- model_client: ModelConfig- headless: bool = True- logs_dir: str = None- to_save_screenshots: bool = False- use_ocr: bool = False- animate_actions: bool = False- tools: Optional[List[ToolConfig]] = None---AgentConfig = AssistantAgentConfig | UserProxyAgentConfig | MultimodalWebSurferAgentConfig---class BaseTerminationConfig(BaseConfig):- termination_type: TerminationTypes- component_type: ComponentTypes = ComponentTypes.TERMINATION---class MaxMessageTerminationConfig(BaseTerminationConfig):- termination_type: TerminationTypes = TerminationTypes.MAX_MESSAGES- max_messages: int---class TextMentionTerminationConfig(BaseTerminationConfig):- termination_type: TerminationTypes = TerminationTypes.TEXT_MENTION- text: str---class StopMessageTerminationConfig(BaseTerminationConfig):- termination_type: TerminationTypes = TerminationTypes.STOP_MESSAGE---class CombinationTerminationConfig(BaseTerminationConfig):- termination_type: TerminationTypes = TerminationTypes.COMBINATION- operator: str- conditions: List["TerminationConfig"]---TerminationConfig = (- MaxMessageTerminationConfig- | TextMentionTerminationConfig- | CombinationTerminationConfig- | StopMessageTerminationConfig-)---class BaseTeamConfig(BaseConfig):- name: str- participants: List[AgentConfig]- team_type: TeamTypes- termination_condition: Optional[TerminationConfig] = None- component_type: ComponentTypes = ComponentTypes.TEAM- max_turns: Optional[int] = None---class RoundRobinTeamConfig(BaseTeamConfig):- team_type: TeamTypes = TeamTypes.ROUND_ROBIN---class SelectorTeamConfig(BaseTeamConfig):- team_type: TeamTypes = TeamTypes.SELECTOR- selector_prompt: Optional[str] = None- model_client: ModelConfig---class MagenticOneTeamConfig(BaseTeamConfig):- team_type: TeamTypes = TeamTypes.MAGENTIC_ONE- model_client: ModelConfig- max_stalls: int = 3- final_answer_prompt: Optional[str] = None---TeamConfig = RoundRobinTeamConfig | SelectorTeamConfig | MagenticOneTeamConfig--class TeamResult(BaseModel):task_result: TaskResultusage: str@@ -202,6 +28,39 @@ class MessageMeta(BaseModel):usage: Optional[List[dict]] = None+class GalleryMetadata(BaseModel):+ author: str+ created_at: datetime+ updated_at: datetime+ version: str+ description: Optional[str] = None+ tags: Optional[List[str]] = None+ license: Optional[str] = None+ homepage: Optional[str] = None+ category: Optional[str] = None+ last_synced: Optional[datetime] = None+++class GalleryComponents(BaseModel):+ agents: List[ComponentModel]+ models: List[ComponentModel]+ tools: List[ComponentModel]+ terminations: List[ComponentModel]+++class GalleryItems(BaseModel):+ teams: List[ComponentModel]+ components: GalleryComponents+++class Gallery(BaseModel):+ id: str+ name: str+ url: Optional[str] = None+ metadata: GalleryMetadata+ items: GalleryItems++# web request/response data models@@ -215,8 +74,3 @@ class SocketMessage(BaseModel):connection_id: strdata: Dict[str, Any]type: str---ComponentConfig = Union[TeamConfig, AgentConfig, ModelConfig, ToolConfig, TerminationConfig]--ComponentConfigInput = Union[str, Path, dict, ComponentConfig]diff --git a/python/packages/autogen-studio/autogenstudio/teammanager.py b/python/packages/autogen-studio/autogenstudio/teammanager.pydeleted file mode 100644index b4ba92460..000000000--- a/python/packages/autogen-studio/autogenstudio/teammanager.py+++ /dev/null@@ -1,73 +0,0 @@-import time-from typing import AsyncGenerator, Callable, Optional, Union--from autogen_agentchat.base import TaskResult-from autogen_agentchat.messages import AgentEvent, ChatMessage-from autogen_core import CancellationToken--from .database import Component, ComponentFactory-from .datamodel import ComponentConfigInput, TeamResult---class TeamManager:- def __init__(self) -> None:- self.component_factory = ComponentFactory()-- async def _create_team(self, team_config: ComponentConfigInput, input_func: Optional[Callable] = None) -> Component:- """Create team instance with common setup logic"""- return await self.component_factory.load(team_config, input_func=input_func)-- def _create_result(self, task_result: TaskResult, start_time: float) -> TeamResult:- """Create TeamResult with timing info"""- return TeamResult(task_result=task_result, usage="", duration=time.time() - start_time)-- async def run_stream(- self,- task: str,- team_config: ComponentConfigInput,- input_func: Optional[Callable] = None,- cancellation_token: Optional[CancellationToken] = None,- ) -> AsyncGenerator[Union[AgentEvent | ChatMessage, ChatMessage, TaskResult], None]:- """Stream the team's execution results"""- start_time = time.time()-- try:- team = await self._create_team(team_config, input_func)- stream = team.run_stream(task=task, cancellation_token=cancellation_token)-- async for message in stream:- if cancellation_token and cancellation_token.is_cancelled():- break-- if isinstance(message, TaskResult):- yield self._create_result(message, start_time)- else:- yield message-- # close agent resources- for agent in team._participants:- if hasattr(agent, "close"):- await agent.close()-- except Exception as e:- raise e-- async def run(- self,- task: str,- team_config: ComponentConfigInput,- input_func: Optional[Callable] = None,- cancellation_token: Optional[CancellationToken] = None,- ) -> TeamResult:- """Original non-streaming run method with optional cancellation"""- start_time = time.time()-- team = await self._create_team(team_config, input_func)- result = await team.run(task=task, cancellation_token=cancellation_token)-- # close agent resources- for agent in team._participants:- if hasattr(agent, "close"):- await agent.close()-- return self._create_result(result, start_time)diff --git a/python/packages/autogen-studio/autogenstudio/teammanager/__init__.py b/python/packages/autogen-studio/autogenstudio/teammanager/__init__.pynew file mode 100644index 000000000..7f202c739--- /dev/null+++ b/python/packages/autogen-studio/autogenstudio/teammanager/__init__.py@@ -0,0 +1,3 @@+from .teammanager import TeamManager++__all__ = ["TeamManager"]diff --git a/python/packages/autogen-studio/autogenstudio/teammanager/teammanager.py b/python/packages/autogen-studio/autogenstudio/teammanager/teammanager.pynew file mode 100644index 000000000..886c228fa--- /dev/null+++ b/python/packages/autogen-studio/autogenstudio/teammanager/teammanager.py@@ -0,0 +1,134 @@+import json+import logging+import time+from pathlib import Path+from typing import AsyncGenerator, Callable, List, Optional, Union++import aiofiles+import yaml+from autogen_agentchat.base import TaskResult, Team+from autogen_agentchat.messages import AgentEvent, ChatMessage+from autogen_core import CancellationToken, Component, ComponentModel++from ..datamodel.types import TeamResult++logger = logging.getLogger(__name__)+++class TeamManager:+ """Manages team operations including loading configs and running teams"""++ @staticmethod+ async def load_from_file(path: Union[str, Path]) -> dict:+ """Load team configuration from JSON/YAML file"""+ path = Path(path)+ if not path.exists():+ raise FileNotFoundError(f"Config file not found: {path}")++ async with aiofiles.open(path) as f:+ content = await f.read()+ if path.suffix == ".json":+ return json.loads(content)+ elif path.suffix in (".yml", ".yaml"):+ return yaml.safe_load(content)+ raise ValueError(f"Unsupported file format: {path.suffix}")++ @staticmethod+ async def load_from_directory(directory: Union[str, Path]) -> List[dict]:+ """Load all team configurations from a directory++ Args:+ directory (Union[str, Path]): Path to directory containing config files++ Returns:+ List[dict]: List of loaded team configurations+ """+ directory = Path(directory)+ configs = []+ valid_extensions = {".json", ".yaml", ".yml"}++ for path in directory.iterdir():+ if path.is_file() and path.suffix.lower() in valid_extensions:+ try:+ config = await TeamManager.load_from_file(path)+ configs.append(config)+ except Exception as e:+ logger.error(f"Failed to load {path}: {e}")++ return configs++ async def _create_team(+ self, team_config: Union[str, Path, dict, ComponentModel], input_func: Optional[Callable] = None+ ) -> Component:+ """Create team instance from config"""+ # Handle different input types+ if isinstance(team_config, (str, Path)):+ config = await self.load_from_file(team_config)+ elif isinstance(team_config, dict):+ config = team_config+ else:+ config = team_config.model_dump()++ # Use Component.load_component directly+ team = Team.load_component(config)++ for agent in team._participants:+ if hasattr(agent, "input_func"):+ agent.input_func = input_func++ # TBD - set input function+ return team++ async def run_stream(+ self,+ task: str,+ team_config: Union[str, Path, dict, ComponentModel],+ input_func: Optional[Callable] = None,+ cancellation_token: Optional[CancellationToken] = None,+ ) -> AsyncGenerator[Union[AgentEvent | ChatMessage, ChatMessage, TaskResult], None]:+ """Stream team execution results"""+ start_time = time.time()+ team = None++ try:+ team = await self._create_team(team_config, input_func)++ async for message in team.run_stream(task=task, cancellation_token=cancellation_token):+ if cancellation_token and cancellation_token.is_cancelled():+ break++ if isinstance(message, TaskResult):+ yield TeamResult(task_result=message, usage="", duration=time.time() - start_time)+ else:+ yield message++ finally:+ # Ensure cleanup happens+ if team and hasattr(team, "_participants"):+ for agent in team._participants:+ if hasattr(agent, "close"):+ await agent.close()++ async def run(+ self,+ task: str,+ team_config: Union[str, Path, dict, ComponentModel],+ input_func: Optional[Callable] = None,+ cancellation_token: Optional[CancellationToken] = None,+ ) -> TeamResult:+ """Run team synchronously"""+ start_time = time.time()+ team = None++ try:+ team = await self._create_team(team_config, input_func)+ result = await team.run(task=task, cancellation_token=cancellation_token)++ return TeamResult(task_result=result, usage="", duration=time.time() - start_time)++ finally:+ # Ensure cleanup happens+ if team and hasattr(team, "_participants"):+ for agent in team._participants:+ if hasattr(agent, "close"):+ await agent.close()diff --git a/python/packages/autogen-studio/autogenstudio/web/app.py b/python/packages/autogen-studio/autogenstudio/web/app.pyindex 2e2ad3337..82caccd98 100644--- a/python/packages/autogen-studio/autogenstudio/web/app.py+++ b/python/packages/autogen-studio/autogenstudio/web/app.py@@ -13,7 +13,7 @@ from ..version import VERSIONfrom .config import settingsfrom .deps import cleanup_managers, init_managersfrom .initialization import AppInitializer-from .routes import agents, models, runs, sessions, teams, tools, ws+from .routes import runs, sessions, teams, ws# Configure logging# logger = logging.getLogger(__name__)@@ -104,26 +104,6 @@ api.include_router(responses={404: {"description": "Not found"}},)-api.include_router(- agents.router,- prefix="/agents",- tags=["agents"],- responses={404: {"description": "Not found"}},-)--api.include_router(- models.router,- prefix="/models",- tags=["models"],- responses={404: {"description": "Not found"}},-)--api.include_router(- tools.router,- prefix="/tools",- tags=["tools"],- responses={404: {"description": "Not found"}},-)api.include_router(ws.router,diff --git a/python/packages/autogen-studio/autogenstudio/web/config.py b/python/packages/autogen-studio/autogenstudio/web/config.pyindex 128edada9..28b88b025 100644--- a/python/packages/autogen-studio/autogenstudio/web/config.py+++ b/python/packages/autogen-studio/autogenstudio/web/config.py@@ -3,7 +3,7 @@ from pydantic_settings import BaseSettingsclass Settings(BaseSettings):- DATABASE_URI: str = "sqlite:///./autogen.db"+ DATABASE_URI: str = "sqlite:///./autogen0404.db"API_DOCS: bool = FalseCLEANUP_INTERVAL: int = 300 # 5 minutesSESSION_TIMEOUT: int = 3600 # 1 hourdiff --git a/python/packages/autogen-studio/autogenstudio/web/deps.py b/python/packages/autogen-studio/autogenstudio/web/deps.pyindex d2e5b6fab..5e7cdd0d2 100644--- a/python/packages/autogen-studio/autogenstudio/web/deps.py+++ b/python/packages/autogen-studio/autogenstudio/web/deps.py@@ -5,7 +5,7 @@ from typing import Optionalfrom fastapi import Depends, HTTPException, status-from ..database import ConfigurationManager, DatabaseManager+from ..database import DatabaseManagerfrom ..teammanager import TeamManagerfrom .config import settingsfrom .managers.connection import WebSocketManager@@ -94,9 +94,7 @@ async def init_managers(database_uri: str, config_dir: str, app_root: str) -> No_db_manager.initialize_database(auto_upgrade=settings.UPGRADE_DATABASE)# init default team config-- _team_config_manager = ConfigurationManager(db_manager=_db_manager)- await _team_config_manager.import_directory(config_dir, settings.DEFAULT_USER_ID, check_exists=True)+ await _db_manager.import_teams_from_directory(config_dir, settings.DEFAULT_USER_ID, check_exists=True)# Initialize connection manager_websocket_manager = WebSocketManager(db_manager=_db_manager)diff --git a/python/packages/autogen-studio/autogenstudio/web/managers/connection.py b/python/packages/autogen-studio/autogenstudio/web/managers/connection.pyindex 271b53d87..67855e997 100644--- a/python/packages/autogen-studio/autogenstudio/web/managers/connection.py+++ b/python/packages/autogen-studio/autogenstudio/web/managers/connection.py@@ -1,5 +1,6 @@import asyncioimport logging+import tracebackfrom datetime import datetime, timezonefrom typing import Any, Callable, Dict, Optional, Unionfrom uuid import UUID@@ -137,12 +138,14 @@ class WebSocketManager:except Exception as e:logger.error(f"Stream error for run {run_id}: {e}")+ traceback.print_exc()await self._handle_stream_error(run_id, e)finally:self._cancellation_tokens.pop(run_id, None)async def _save_message(self, run_id: UUID, message: Union[AgentEvent | ChatMessage, ChatMessage]) -> None:"""Save a message to the database"""+run = await self._get_run(run_id)if run:db_message = Message(diff --git a/python/packages/autogen-studio/autogenstudio/web/routes/models.py b/python/packages/autogen-studio/autogenstudio/web/routes/models.pydeleted file mode 100644index f041e52cb..000000000--- a/python/packages/autogen-studio/autogenstudio/web/routes/models.py+++ /dev/null@@ -1,42 +0,0 @@-# api/routes/models.py-from typing import Dict--from fastapi import APIRouter, Depends, HTTPException-from openai import OpenAIError--from ...datamodel import Model-from ..deps import get_db--router = APIRouter()--[email protected]("/")-async def list_models(user_id: str, db=Depends(get_db)) -> Dict:- """List all models for a user"""- response = db.get(Model, filters={"user_id": user_id})- return {"status": True, "data": response.data}--[email protected]("/{model_id}")-async def get_model(model_id: int, user_id: str, db=Depends(get_db)) -> Dict:- """Get a specific model"""- response = db.get(Model, filters={"id": model_id, "user_id": user_id})- if not response.status or not response.data:- raise HTTPException(status_code=404, detail="Model not found")- return {"status": True, "data": response.data[0]}--[email protected]("/")-async def create_model(model: Model, db=Depends(get_db)) -> Dict:- """Create a new model"""- response = db.upsert(model)- if not response.status:- raise HTTPException(status_code=400, detail=response.message)- return {"status": True, "data": response.data}--[email protected]("/{model_id}")-async def delete_model(model_id: int, user_id: str, db=Depends(get_db)) -> Dict:- """Delete a model"""- db.delete(filters={"id": model_id, "user_id": user_id}, model_class=Model)- return {"status": True, "message": "Model deleted successfully"}diff --git a/python/packages/autogen-studio/autogenstudio/web/routes/tools.py b/python/packages/autogen-studio/autogenstudio/web/routes/tools.pydeleted file mode 100644index da2ae7733..000000000--- a/python/packages/autogen-studio/autogenstudio/web/routes/tools.py+++ /dev/null@@ -1,41 +0,0 @@-# api/routes/tools.py-from typing import Dict--from fastapi import APIRouter, Depends, HTTPException--from ...datamodel import Tool-from ..deps import get_db--router = APIRouter()--[email protected]("/")-async def list_tools(user_id: str, db=Depends(get_db)) -> Dict:- """List all tools for a user"""- response = db.get(Tool, filters={"user_id": user_id})- return {"status": True, "data": response.data}--[email protected]("/{tool_id}")-async def get_tool(tool_id: int, user_id: str, db=Depends(get_db)) -> Dict:- """Get a specific tool"""- response = db.get(Tool, filters={"id": tool_id, "user_id": user_id})- if not response.status or not response.data:- raise HTTPException(status_code=404, detail="Tool not found")- return {"status": True, "data": response.data[0]}--[email protected]("/")-async def create_tool(tool: Tool, db=Depends(get_db)) -> Dict:- """Create a new tool"""- response = db.upsert(tool)- if not response.status:- raise HTTPException(status_code=400, detail=response.message)- return {"status": True, "data": response.data}--[email protected]("/{tool_id}")-async def delete_tool(tool_id: int, user_id: str, db=Depends(get_db)) -> Dict:- """Delete a tool"""- db.delete(filters={"id": tool_id, "user_id": user_id}, model_class=Tool)- return {"status": True, "message": "Tool deleted successfully"}diff --git a/python/packages/autogen-studio/frontend/src/components/types/datamodel.ts b/python/packages/autogen-studio/frontend/src/components/types/datamodel.tsindex b502f04c8..195950f08 100644--- a/python/packages/autogen-studio/frontend/src/components/types/datamodel.ts+++ b/python/packages/autogen-studio/frontend/src/components/types/datamodel.ts@@ -1,3 +1,22 @@+// Base Component System++export type ComponentTypes =+ | "team"+ | "agent"+ | "model"+ | "tool"+ | "termination";+export interface Component<T extends ComponentConfig> {+ provider: string;+ component_type: ComponentTypes;+ version?: number;+ component_version?: number;+ description?: string | null;+ config: T;+ label?: string;+}++// Message Typesexport interface RequestUsage {prompt_tokens: number;completion_tokens: number;@@ -11,7 +30,7 @@ export interface ImageContent {export interface FunctionCall {id: string;- arguments: string; // JSON string+ arguments: string;name: string;}@@ -20,13 +39,11 @@ export interface FunctionExecutionResult {content: string;}-// Base message configuration (maps to Python BaseMessage)export interface BaseMessageConfig {source: string;models_usage?: RequestUsage;}-// Message configurations (mapping directly to Python classes)export interface TextMessageConfig extends BaseMessageConfig {content: string;}@@ -52,17 +69,6 @@ export interface ToolCallResultMessageConfig extends BaseMessageConfig {content: FunctionExecutionResult[];}-// Message type unions (matching Python type aliases)-export type InnerMessageConfig =- | ToolCallMessageConfig- | ToolCallResultMessageConfig;--export type ChatMessageConfig =- | TextMessageConfig- | MultiModalMessageConfig- | StopMessageConfig- | HandoffMessageConfig;-export type AgentMessageConfig =| TextMessageConfig| MultiModalMessageConfig@@ -71,210 +77,191 @@ export type AgentMessageConfig =| ToolCallMessageConfig| ToolCallResultMessageConfig;-// Database model-export interface DBModel {- id?: number;- user_id?: string;- created_at?: string;- updated_at?: string;- version?: number;-}--export interface Message extends DBModel {- config: AgentMessageConfig;- session_id: number;- run_id: string;+// Tool Configs+export interface FunctionToolConfig {+ source_code: string;+ name: string;+ description: string;+ global_imports: any[]; // Sequence[Import] equivalent+ has_cancellation_support: boolean;}-export interface Session extends DBModel {- name: string;- team_id?: number;+// Provider-based Configs+export interface SelectorGroupChatConfig {+ participants: Component<AgentConfig>[];+ model_client: Component<ModelConfig>;+ termination_condition?: Component<TerminationConfig>;+ max_turns?: number;+ selector_prompt: string;+ allow_repeated_speaker: boolean;}-export interface SessionRuns {- runs: Run[];+export interface RoundRobinGroupChatConfig {+ participants: Component<AgentConfig>[];+ termination_condition?: Component<TerminationConfig>;+ max_turns?: number;}-export interface BaseConfig {- component_type: string;- version?: string;+export interface MultimodalWebSurferConfig {+ name: string;+ model_client: Component<ModelConfig>;+ downloads_folder?: string;description?: string;+ debug_dir?: string;+ headless?: boolean;+ start_page?: string;+ animate_actions?: boolean;+ to_save_screenshots?: boolean;+ use_ocr?: boolean;+ browser_channel?: string;+ browser_data_dir?: string;+ to_resize_viewport?: boolean;+}++export interface AssistantAgentConfig {+ name: string;+ model_client: Component<ModelConfig>;+ tools?: Component<ToolConfig>[];+ handoffs?: any[]; // HandoffBase | str equivalent+ model_context?: Component<ChatCompletionContextConfig>;+ description: string;+ system_message?: string;+ reflect_on_tool_use: boolean;+ tool_call_summary_format: string;}-export interface WebSocketMessage {- type: "message" | "result" | "completion" | "input_request" | "error";- data?: AgentMessageConfig | TaskResult;- status?: RunStatus;- error?: string;- timestamp?: string;+export interface UserProxyAgentConfig {+ name: string;+ description: string;}-export interface TaskResult {- messages: AgentMessageConfig[];- stop_reason?: string;+// Model Configs+export interface ModelInfo {+ vision: boolean;+ function_calling: boolean;+ json_output: boolean;+ family: string;}-export type ModelTypes =- | "OpenAIChatCompletionClient"- | "AzureOpenAIChatCompletionClient";--export type AgentTypes =- | "AssistantAgent"- | "UserProxyAgent"- | "MultimodalWebSurfer"- | "FileSurfer"- | "MagenticOneCoderAgent";--export type ToolTypes = "PythonFunction";--export type TeamTypes =- | "RoundRobinGroupChat"- | "SelectorGroupChat"- | "MagenticOneGroupChat";--export type TerminationTypes =- | "MaxMessageTermination"- | "StopMessageTermination"- | "TextMentionTermination"- | "TimeoutTermination"- | "CombinationTermination";--export type ComponentTypes =- | "team"- | "agent"- | "model"- | "tool"- | "termination";--export type ComponentConfigTypes =- | TeamConfig- | AgentConfig- | ModelConfig- | ToolConfig- | TerminationConfig;+export interface CreateArgumentsConfig {+ frequency_penalty?: number;+ logit_bias?: Record<string, number>;+ max_tokens?: number;+ n?: number;+ presence_penalty?: number;+ response_format?: any; // ResponseFormat equivalent+ seed?: number;+ stop?: string | string[];+ temperature?: number;+ top_p?: number;+ user?: string;+}-export interface BaseModelConfig extends BaseConfig {+export interface BaseOpenAIClientConfig extends CreateArgumentsConfig {model: string;- model_type: ModelTypes;api_key?: string;+ timeout?: number;+ max_retries?: number;+ model_capabilities?: any; // ModelCapabilities equivalent+ model_info?: ModelInfo;+}++export interface OpenAIClientConfig extends BaseOpenAIClientConfig {+ organization?: string;base_url?: string;}-export interface AzureOpenAIModelConfig extends BaseModelConfig {- model_type: "AzureOpenAIChatCompletionClient";- azure_deployment: string;- api_version: string;+export interface AzureOpenAIClientConfig extends BaseOpenAIClientConfig {azure_endpoint: string;- azure_ad_token_provider: string;+ azure_deployment?: string;+ api_version: string;+ azure_ad_token?: string;+ azure_ad_token_provider?: Component<any>;}-export interface OpenAIModelConfig extends BaseModelConfig {- model_type: "OpenAIChatCompletionClient";+export interface UnboundedChatCompletionContextConfig {+ // Empty in example but could have props}-export type ModelConfig = AzureOpenAIModelConfig | OpenAIModelConfig;--export interface BaseToolConfig extends BaseConfig {- name: string;- description: string;- content: string;- tool_type: ToolTypes;-}--export interface PythonFunctionToolConfig extends BaseToolConfig {- tool_type: "PythonFunction";+export interface OrTerminationConfig {+ conditions: Component<TerminationConfig>[];}-export type ToolConfig = PythonFunctionToolConfig;--export interface BaseAgentConfig extends BaseConfig {- name: string;- agent_type: AgentTypes;- system_message?: string;- model_client?: ModelConfig;- tools?: ToolConfig[];- description?: string;+export interface MaxMessageTerminationConfig {+ max_messages: number;}-export interface AssistantAgentConfig extends BaseAgentConfig {- agent_type: "AssistantAgent";+export interface TextMentionTerminationConfig {+ text: string;}-export interface UserProxyAgentConfig extends BaseAgentConfig {- agent_type: "UserProxyAgent";-}+// Config type unions based on provider+export type TeamConfig = SelectorGroupChatConfig | RoundRobinGroupChatConfig;-export interface MultimodalWebSurferAgentConfig extends BaseAgentConfig {- agent_type: "MultimodalWebSurfer";-}+export type AgentConfig =+ | MultimodalWebSurferConfig+ | AssistantAgentConfig+ | UserProxyAgentConfig;-export interface FileSurferAgentConfig extends BaseAgentConfig {- agent_type: "FileSurfer";-}+export type ModelConfig = OpenAIClientConfig | AzureOpenAIClientConfig;-export interface MagenticOneCoderAgentConfig extends BaseAgentConfig {- agent_type: "MagenticOneCoderAgent";-}+export type ToolConfig = FunctionToolConfig;-export type AgentConfig =- | AssistantAgentConfig- | UserProxyAgentConfig- | MultimodalWebSurferAgentConfig- | FileSurferAgentConfig- | MagenticOneCoderAgentConfig;+export type ChatCompletionContextConfig = UnboundedChatCompletionContextConfig;-// export interface TerminationConfig extends BaseConfig {-// termination_type: TerminationTypes;-// max_messages?: number;-// text?: string;-// }+export type TerminationConfig =+ | OrTerminationConfig+ | MaxMessageTerminationConfig+ | TextMentionTerminationConfig;-export interface BaseTerminationConfig extends BaseConfig {- termination_type: TerminationTypes;-}+export type ComponentConfig =+ | TeamConfig+ | AgentConfig+ | ModelConfig+ | ToolConfig+ | TerminationConfig+ | ChatCompletionContextConfig;-export interface MaxMessageTerminationConfig extends BaseTerminationConfig {- termination_type: "MaxMessageTermination";- max_messages: number;+// DB Models+export interface DBModel {+ id?: number;+ user_id?: string;+ created_at?: string;+ updated_at?: string;+ version?: number;}-export interface TextMentionTerminationConfig extends BaseTerminationConfig {- termination_type: "TextMentionTermination";- text: string;+export interface Message extends DBModel {+ config: AgentMessageConfig;+ session_id: number;+ run_id: string;}-export interface CombinationTerminationConfig extends BaseTerminationConfig {- termination_type: "CombinationTermination";- operator: "and" | "or";- conditions: TerminationConfig[];+export interface Team extends DBModel {+ component: Component<TeamConfig>;}-export type TerminationConfig =- | MaxMessageTerminationConfig- | TextMentionTerminationConfig- | CombinationTerminationConfig;--export interface BaseTeamConfig extends BaseConfig {+export interface Session extends DBModel {name: string;- participants: AgentConfig[];- team_type: TeamTypes;- termination_condition?: TerminationConfig;+ team_id?: number;}-export interface RoundRobinGroupChatConfig extends BaseTeamConfig {- team_type: "RoundRobinGroupChat";+// Runtime Types+export interface SessionRuns {+ runs: Run[];}-export interface SelectorGroupChatConfig extends BaseTeamConfig {- team_type: "SelectorGroupChat";- selector_prompt: string;- model_client: ModelConfig;+export interface WebSocketMessage {+ type: "message" | "result" | "completion" | "input_request" | "error";+ data?: AgentMessageConfig | TaskResult;+ status?: RunStatus;+ error?: string;+ timestamp?: string;}-export type TeamConfig = RoundRobinGroupChatConfig | SelectorGroupChatConfig;--export interface Team extends DBModel {- config: TeamConfig;+export interface TaskResult {+ messages: AgentMessageConfig[];+ stop_reason?: string;}export interface TeamResult {@@ -290,13 +277,13 @@ export interface Run {status: RunStatus;task: AgentMessageConfig;team_result: TeamResult | null;- messages: Message[]; // Change to Message[]+ messages: Message[];error_message?: string;}export type RunStatus =| "created"- | "active" // covers 'streaming'+ | "active"| "awaiting_input"| "timeout"| "complete"diff --git a/python/packages/autogen-studio/frontend/src/components/types/guards.ts b/python/packages/autogen-studio/frontend/src/components/types/guards.tsnew file mode 100644index 000000000..63e6a5a1c--- /dev/null+++ b/python/packages/autogen-studio/frontend/src/components/types/guards.ts@@ -0,0 +1,231 @@+import type {+ Component,+ ComponentConfig,+ TeamConfig,+ AgentConfig,+ ModelConfig,+ ToolConfig,+ TerminationConfig,+ ChatCompletionContextConfig,+ SelectorGroupChatConfig,+ RoundRobinGroupChatConfig,+ MultimodalWebSurferConfig,+ AssistantAgentConfig,+ UserProxyAgentConfig,+ OpenAIClientConfig,+ AzureOpenAIClientConfig,+ FunctionToolConfig,+ OrTerminationConfig,+ MaxMessageTerminationConfig,+ TextMentionTerminationConfig,+ UnboundedChatCompletionContextConfig,+} from "./datamodel";++// Provider constants+const PROVIDERS = {+ // Teams+ ROUND_ROBIN_TEAM: "autogen_agentchat.teams.RoundRobinGroupChat",+ SELECTOR_TEAM: "autogen_agentchat.teams.SelectorGroupChat",++ // Agents+ ASSISTANT_AGENT: "autogen_agentchat.agents.AssistantAgent",+ USER_PROXY: "autogen_agentchat.agents.UserProxyAgent",+ WEB_SURFER: "autogen_ext.agents.web_surfer.MultimodalWebSurfer",++ // Models+ OPENAI: "autogen_ext.models.openai.OpenAIChatCompletionClient",+ AZURE_OPENAI:+ "autogen_ext.models.azure_openai.AzureOpenAIChatCompletionClient",++ // Tools+ FUNCTION_TOOL: "autogen_core.tools.FunctionTool",++ // Termination+ OR_TERMINATION: "autogen_agentchat.base.OrTerminationCondition",+ MAX_MESSAGE: "autogen_agentchat.conditions.MaxMessageTermination",+ TEXT_MENTION: "autogen_agentchat.conditions.TextMentionTermination",++ // Contexts+ UNBOUNDED_CONTEXT:+ "autogen_core.model_context.UnboundedChatCompletionContext",+} as const;++// Provider type and mapping+export type Provider = (typeof PROVIDERS)[keyof typeof PROVIDERS];++type ProviderToConfig = {+ // Teams+ [PROVIDERS.SELECTOR_TEAM]: SelectorGroupChatConfig;+ [PROVIDERS.ROUND_ROBIN_TEAM]: RoundRobinGroupChatConfig;++ // Agents+ [PROVIDERS.ASSISTANT_AGENT]: AssistantAgentConfig;+ [PROVIDERS.USER_PROXY]: UserProxyAgentConfig;+ [PROVIDERS.WEB_SURFER]: MultimodalWebSurferConfig;++ // Models+ [PROVIDERS.OPENAI]: OpenAIClientConfig;+ [PROVIDERS.AZURE_OPENAI]: AzureOpenAIClientConfig;++ // Tools+ [PROVIDERS.FUNCTION_TOOL]: FunctionToolConfig;++ // Termination+ [PROVIDERS.OR_TERMINATION]: OrTerminationConfig;+ [PROVIDERS.MAX_MESSAGE]: MaxMessageTerminationConfig;+ [PROVIDERS.TEXT_MENTION]: TextMentionTerminationConfig;++ // Contexts+ [PROVIDERS.UNBOUNDED_CONTEXT]: UnboundedChatCompletionContextConfig;+};++// Helper type to get config type from provider+type ConfigForProvider<P extends Provider> = P extends keyof ProviderToConfig+ ? ProviderToConfig[P]+ : never;++export function isComponent(value: any): value is Component<ComponentConfig> {+ return (+ value &&+ typeof value === "object" &&+ "provider" in value &&+ "component_type" in value &&+ "config" in value+ );+}+// Generic component type guard+function isComponentOfType<P extends Provider>(+ component: Component<ComponentConfig>,+ provider: P+): component is Component<ConfigForProvider<P>> {+ return component.provider === provider;+}++// Base component type guards+export function isTeamComponent(+ component: Component<ComponentConfig>+): component is Component<TeamConfig> {+ return component.component_type === "team";+}++export function isAgentComponent(+ component: Component<ComponentConfig>+): component is Component<AgentConfig> {+ return component.component_type === "agent";+}++export function isModelComponent(+ component: Component<ComponentConfig>+): component is Component<ModelConfig> {+ return component.component_type === "model";+}++export function isToolComponent(+ component: Component<ComponentConfig>+): component is Component<ToolConfig> {+ return component.component_type === "tool";+}++export function isTerminationComponent(+ component: Component<ComponentConfig>+): component is Component<TerminationConfig> {+ return component.component_type === "termination";+}++// export function isChatCompletionContextComponent(+// component: Component<ComponentConfig>+// ): component is Component<ChatCompletionContextConfig> {+// return component.component_type === "chat_completion_context";+// }++// Team provider guards with proper type narrowing+export function isRoundRobinTeam(+ component: Component<ComponentConfig>+): component is Component<RoundRobinGroupChatConfig> {+ return isComponentOfType(component, PROVIDERS.ROUND_ROBIN_TEAM);+}++export function isSelectorTeam(+ component: Component<ComponentConfig>+): component is Component<SelectorGroupChatConfig> {+ return isComponentOfType(component, PROVIDERS.SELECTOR_TEAM);+}++// Agent provider guards with proper type narrowing+export function isAssistantAgent(+ component: Component<ComponentConfig>+): component is Component<AssistantAgentConfig> {+ return isComponentOfType(component, PROVIDERS.ASSISTANT_AGENT);+}++export function isUserProxyAgent(+ component: Component<ComponentConfig>+): component is Component<UserProxyAgentConfig> {+ return isComponentOfType(component, PROVIDERS.USER_PROXY);+}++export function isWebSurferAgent(+ component: Component<ComponentConfig>+): component is Component<MultimodalWebSurferConfig> {+ return isComponentOfType(component, PROVIDERS.WEB_SURFER);+}++// Model provider guards with proper type narrowing+export function isOpenAIModel(+ component: Component<ComponentConfig>+): component is Component<OpenAIClientConfig> {+ return isComponentOfType(component, PROVIDERS.OPENAI);+}++export function isAzureOpenAIModel(+ component: Component<ComponentConfig>+): component is Component<AzureOpenAIClientConfig> {+ return isComponentOfType(component, PROVIDERS.AZURE_OPENAI);+}++// Tool provider guards with proper type narrowing+export function isFunctionTool(+ component: Component<ComponentConfig>+): component is Component<FunctionToolConfig> {+ return isComponentOfType(component, PROVIDERS.FUNCTION_TOOL);+}++// Termination provider guards with proper type narrowing+export function isOrTermination(+ component: Component<ComponentConfig>+): component is Component<OrTerminationConfig> {+ return isComponentOfType(component, PROVIDERS.OR_TERMINATION);+}++export function isMaxMessageTermination(+ component: Component<ComponentConfig>+): component is Component<MaxMessageTerminationConfig> {+ return isComponentOfType(component, PROVIDERS.MAX_MESSAGE);+}++export function isTextMentionTermination(+ component: Component<ComponentConfig>+): component is Component<TextMentionTerminationConfig> {+ return isComponentOfType(component, PROVIDERS.TEXT_MENTION);+}++// Context provider guards with proper type narrowing+export function isUnboundedContext(+ component: Component<ComponentConfig>+): component is Component<UnboundedChatCompletionContextConfig> {+ return isComponentOfType(component, PROVIDERS.UNBOUNDED_CONTEXT);+}++// Runtime assertions+export function assertComponentType<P extends Provider>(+ component: Component<ComponentConfig>,+ provider: P+): asserts component is Component<ConfigForProvider<P>> {+ if (!isComponentOfType(component, provider)) {+ throw new Error(+ `Expected component with provider ${provider}, got ${component.provider}`+ );+ }+}++export { PROVIDERS };diff --git a/python/packages/autogen-studio/frontend/src/components/views/atoms.tsx b/python/packages/autogen-studio/frontend/src/components/views/atoms.tsxindex b3db483b4..8fac8ecdc 100644--- a/python/packages/autogen-studio/frontend/src/components/views/atoms.tsx+++ b/python/packages/autogen-studio/frontend/src/components/views/atoms.tsx@@ -1,5 +1,6 @@import React, { memo, useState } from "react";import { Loader2, Maximize2, Minimize2, X } from "lucide-react";+import ReactMarkdown from "react-markdown";export const LoadingIndicator = ({ size = 16 }: { size: number }) => (<div className="inline-flex items-center gap-2 text-accent mr-2">@@ -80,7 +81,8 @@ export const TruncatableText = memo(${className}`}>- {displayContent}+ {/* {displayContent} */}+ <ReactMarkdown>{displayContent}</ReactMarkdown>{shouldTruncate && !isExpanded && (<div className="absolute bottom-0 left-0 right-0 h-24 bg-gradient-to-t from-secondary/20 to-transparent" />)}diff --git a/python/packages/autogen-studio/frontend/src/components/views/deploy/guides/guides.tsx b/python/packages/autogen-studio/frontend/src/components/views/deploy/guides/guides.tsxindex 4da98faf7..bb561719e 100644--- a/python/packages/autogen-studio/frontend/src/components/views/deploy/guides/guides.tsx+++ b/python/packages/autogen-studio/frontend/src/components/views/deploy/guides/guides.tsx@@ -3,14 +3,8 @@ import { Copy } from "lucide-react";import { Guide } from "../types";import PythonGuide from "./python";import DockerGuide from "./docker";-import { PrismLight as SyntaxHighlighter } from "react-syntax-highlighter";-import js from "react-syntax-highlighter/dist/esm/languages/prism/javascript";-import python from "react-syntax-highlighter/dist/esm/languages/prism/python";-import { oneDark } from "react-syntax-highlighter/dist/esm/styles/prism";--SyntaxHighlighter.registerLanguage("javascript", js);-SyntaxHighlighter.registerLanguage("python", python);+import { MonacoEditor } from "../../monaco";interface GuideContentProps {guide: Guide;@@ -48,6 +42,8 @@ interface CodeSectionProps {language?: string;}+const editorRef = React.createRef<any>();+export const CodeSection: React.FC<CodeSectionProps> = ({title,description,@@ -57,19 +53,16 @@ export const CodeSection: React.FC<CodeSectionProps> = ({}) => (<section className="mt-6 bg-seco"><h2 className="text-md font-semibold mb-3">{title}</h2>- {description && <p className=" mb-3">{description}</p>}+ {description && <div className=" mb-3">{description}</div>}{code && (- <div className="relative bg-secondary text-sm p-4 rounded overflow-auto scroll">+ <div className="relative bg-secondary text-sm p-4 rounded overflow-auto scroll h-72">+ <MonacoEditor language={language} editorRef={editorRef} value={code} /><buttononClick={() => onCopy(code)}className="absolute right-2 top-2 p-2 bg-secondary hover:bg-primary rounded-md"><Copy className="w-4 h-4 hover:text-accent transition duration-100" /></button>- {/* overflow scroll custom style */}- <SyntaxHighlighter language={language} wrapLines={true} style={oneDark}>- {code}- </SyntaxHighlighter></div>)}</section>diff --git a/python/packages/autogen-studio/frontend/src/components/views/deploy/guides/python.tsx b/python/packages/autogen-studio/frontend/src/components/views/deploy/guides/python.tsxindex 8ad34818a..fa0c79e4f 100644--- a/python/packages/autogen-studio/frontend/src/components/views/deploy/guides/python.tsx+++ b/python/packages/autogen-studio/frontend/src/components/views/deploy/guides/python.tsx@@ -29,13 +29,37 @@ const PythonGuide: React.FC = () => {<Download className="h-4 w-4 inline-block" />{" "}</div>+ {/* Basic Usage */}+ <CodeSection+ title="1. Build Your Team in Python, Export as JSON"+ description="Here is an example of building an Agent Team in python and exporting it as a JSON file."+ code={`+from autogen_agentchat.agents import AssistantAgent+from autogen_agentchat.teams import RoundRobinGroupChat+from autogen_agentchat.ui import Console+from autogen_ext.models.openai import OpenAIChatCompletionClient+from autogen_agentchat.conditions import TextMentionTermination++agent = AssistantAgent(+ name="weather_agent",+ model_client=OpenAIChatCompletionClient(+ model="gpt-4o-mini",+ ),+ )+agent_team = RoundRobinGroupChat([agent], termination_condition=TextMentionTermination("TERMINATE"))+config = agent_team.dump_component()+print(config.model_dump_json())`}+ onCopy={copyToClipboard}+ />+{/* Installation Steps */}<div className="space-y-6">{/* Basic Usage */}<CodeSection- title="1. Run a Team in Python"+ title="2. Run a Team in Python"description="Here's a simple example of using the TeamManager class from AutoGen Studio in your python code."- code={`from autogenstudio.teammanager import TeamManager+ code={`+from autogenstudio.teammanager import TeamManager# Initialize the TeamManagermanager = TeamManager()@@ -50,7 +74,7 @@ print(result)`}/><CodeSection- title="2. Serve a Team as a REST API"+ title="3. Serve a Team as a REST API"description=<div>AutoGen Studio offers a convenience CLI command to serve a team as aREST API endpoint.{" "}diff --git a/python/packages/autogen-studio/frontend/src/components/views/gallery/default_gallery.json b/python/packages/autogen-studio/frontend/src/components/views/gallery/default_gallery.jsonnew file mode 100644index 000000000..7c876e894--- /dev/null+++ b/python/packages/autogen-studio/frontend/src/components/views/gallery/default_gallery.json@@ -0,0 +1,539 @@+{+ "id": "gallery_default",+ "name": "Default Component Gallery",+ "url": null,+ "metadata": {+ "author": "AutoGen Team",+ "created_at": "2025-01-29T22:13:58.687387",+ "updated_at": "2025-01-29T22:13:58.715730",+ "version": "1.0.0",+ "description": "A default gallery containing basic components for human-in-loop conversations",+ "tags": ["human-in-loop", "assistant"],+ "license": "MIT",+ "homepage": null,+ "category": "conversation",+ "last_synced": null+ },+ "items": {+ "teams": [+ {+ "provider": "autogen_agentchat.teams.RoundRobinGroupChat",+ "component_type": "team",+ "version": 1,+ "component_version": 1,+ "description": "A team that runs a group chat with participants taking turns in a round-robin fashion\n to publish a message to all.",+ "label": "RoundRobinGroupChat",+ "config": {+ "participants": [+ {+ "provider": "autogen_agentchat.agents.AssistantAgent",+ "component_type": "agent",+ "version": 1,+ "component_version": 1,+ "description": "An agent that provides assistance with tool use.",+ "label": "AssistantAgent",+ "config": {+ "name": "assistant_agent",+ "model_client": {+ "provider": "autogen_ext.models.openai.OpenAIChatCompletionClient",+ "component_type": "model",+ "version": 1,+ "component_version": 1,+ "description": "Chat completion client for OpenAI hosted models.",+ "label": "OpenAIChatCompletionClient",+ "config": {+ "model": "gpt-4o-mini"+ }+ },+ "tools": [+ {+ "provider": "autogen_core.tools.FunctionTool",+ "component_type": "tool",+ "version": 1,+ "component_version": 1,+ "description": "Create custom tools by wrapping standard Python functions.",+ "label": "FunctionTool",+ "config": {+ "source_code": "def calculator(a: float, b: float, operator: str) -> str:\n try:\n if operator == '+':\n return str(a + b)\n elif operator == '-':\n return str(a - b)\n elif operator == '*':\n return str(a * b)\n elif operator == '/':\n if b == 0:\n return 'Error: Division by zero'\n return str(a / b)\n else:\n return 'Error: Invalid operator. Please use +, -, *, or /'\n except Exception as e:\n return f'Error: {str(e)}'\n",+ "name": "calculator",+ "description": "A simple calculator that performs basic arithmetic operations",+ "global_imports": [],+ "has_cancellation_support": false+ }+ }+ ],+ "handoffs": [],+ "model_context": {+ "provider": "autogen_core.model_context.UnboundedChatCompletionContext",+ "component_type": "chat_completion_context",+ "version": 1,+ "component_version": 1,+ "description": "An unbounded chat completion context that keeps a view of the all the messages.",+ "label": "UnboundedChatCompletionContext",+ "config": {}+ },+ "description": "An agent that provides assistance with ability to use tools.",+ "system_message": "You are a helpful assistant. Solve tasks carefully. When done, say TERMINATE.",+ "model_client_stream": false,+ "reflect_on_tool_use": false,+ "tool_call_summary_format": "{result}"+ }+ }+ ],+ "termination_condition": {+ "provider": "autogen_agentchat.base.OrTerminationCondition",+ "component_type": "termination",+ "version": 1,+ "component_version": 1,+ "label": "OrTerminationCondition",+ "config": {+ "conditions": [+ {+ "provider": "autogen_agentchat.conditions.TextMentionTermination",+ "component_type": "termination",+ "version": 1,+ "component_version": 1,+ "description": "Terminate the conversation if a specific text is mentioned.",+ "label": "TextMentionTermination",+ "config": {+ "text": "TERMINATE"+ }+ },+ {+ "provider": "autogen_agentchat.conditions.MaxMessageTermination",+ "component_type": "termination",+ "version": 1,+ "component_version": 1,+ "description": "Terminate the conversation after a maximum number of messages have been exchanged.",+ "label": "MaxMessageTermination",+ "config": {+ "max_messages": 10+ }+ }+ ]+ }+ }+ }+ },+ {+ "provider": "autogen_agentchat.teams.SelectorGroupChat",+ "component_type": "team",+ "version": 1,+ "component_version": 1,+ "description": "A group chat team that have participants takes turn to publish a message\n to all, using a ChatCompletion model to select the next speaker after each message.",+ "label": "Web Agents (Operator)",+ "config": {+ "participants": [+ {+ "provider": "autogen_ext.agents.web_surfer.MultimodalWebSurfer",+ "component_type": "agent",+ "version": 1,+ "component_version": 1,+ "description": "MultimodalWebSurfer is a multimodal agent that acts as a web surfer that can search the web and visit web pages.",+ "label": "MultimodalWebSurfer",+ "config": {+ "name": "websurfer_agent",+ "model_client": {+ "provider": "autogen_ext.models.openai.OpenAIChatCompletionClient",+ "component_type": "model",+ "version": 1,+ "component_version": 1,+ "description": "Chat completion client for OpenAI hosted models.",+ "label": "OpenAIChatCompletionClient",+ "config": {+ "model": "gpt-4o-mini"+ }+ },+ "description": "an agent that solves tasks by browsing the web",+ "headless": true,+ "start_page": "https://www.bing.com/",+ "animate_actions": false,+ "to_save_screenshots": false,+ "use_ocr": false,+ "to_resize_viewport": true+ }+ },+ {+ "provider": "autogen_agentchat.agents.AssistantAgent",+ "component_type": "agent",+ "version": 1,+ "component_version": 1,+ "description": "An agent that provides assistance with tool use.",+ "label": "AssistantAgent",+ "config": {+ "name": "assistant_agent",+ "model_client": {+ "provider": "autogen_ext.models.openai.OpenAIChatCompletionClient",+ "component_type": "model",+ "version": 1,+ "component_version": 1,+ "description": "Chat completion client for OpenAI hosted models.",+ "label": "OpenAIChatCompletionClient",+ "config": {+ "model": "gpt-4o-mini"+ }+ },+ "tools": [],+ "handoffs": [],+ "model_context": {+ "provider": "autogen_core.model_context.UnboundedChatCompletionContext",+ "component_type": "chat_completion_context",+ "version": 1,+ "component_version": 1,+ "description": "An unbounded chat completion context that keeps a view of the all the messages.",+ "label": "UnboundedChatCompletionContext",+ "config": {}+ },+ "description": "an agent that verifies and summarizes information",+ "system_message": "You are a task verification assistant who is working with a web surfer agent to solve tasks. At each point, check if the task has been completed as requested by the user. If the websurfer_agent responds and the task has not yet been completed, respond with what is left to do and then say 'keep going'. If and only when the task has been completed, summarize and present a final answer that directly addresses the user task in detail and then respond with TERMINATE.",+ "model_client_stream": false,+ "reflect_on_tool_use": false,+ "tool_call_summary_format": "{result}"+ }+ },+ {+ "provider": "autogen_agentchat.agents.UserProxyAgent",+ "component_type": "agent",+ "version": 1,+ "component_version": 1,+ "description": "An agent that can represent a human user through an input function.",+ "label": "UserProxyAgent",+ "config": {+ "name": "user_proxy",+ "description": "a human user that should be consulted only when the assistant_agent is unable to verify the information provided by the websurfer_agent"+ }+ }+ ],+ "model_client": {+ "provider": "autogen_ext.models.openai.OpenAIChatCompletionClient",+ "component_type": "model",+ "version": 1,+ "component_version": 1,+ "description": "Chat completion client for OpenAI hosted models.",+ "label": "OpenAIChatCompletionClient",+ "config": {+ "model": "gpt-4o-mini"+ }+ },+ "termination_condition": {+ "provider": "autogen_agentchat.base.OrTerminationCondition",+ "component_type": "termination",+ "version": 1,+ "component_version": 1,+ "label": "OrTerminationCondition",+ "config": {+ "conditions": [+ {+ "provider": "autogen_agentchat.conditions.MaxMessageTermination",+ "component_type": "termination",+ "version": 1,+ "component_version": 1,+ "description": "Terminate the conversation after a maximum number of messages have been exchanged.",+ "label": "MaxMessageTermination",+ "config": {+ "max_messages": 20+ }+ },+ {+ "provider": "autogen_agentchat.conditions.TextMentionTermination",+ "component_type": "termination",+ "version": 1,+ "component_version": 1,+ "description": "Terminate the conversation if a specific text is mentioned.",+ "label": "TextMentionTermination",+ "config": {+ "text": "TERMINATE"+ }+ }+ ]+ }+ },+ "selector_prompt": "You are the cordinator of role play game. The following roles are available:\n{roles}. Given a task, the websurfer_agent will be tasked to address it by browsing the web and providing information. The assistant_agent will be tasked with verifying the information provided by the websurfer_agent and summarizing the information to present a final answer to the user. \nIf the task needs assistance from a human user (e.g., providing feedback, preferences, or the task is stalled), you should select the user_proxy role to provide the necessary information.\n\nRead the following conversation. Then select the next role from {participants} to play. Only return the role.\n\n{history}\n\nRead the above conversation. Then select the next role from {participants} to play. Only return the role.",+ "allow_repeated_speaker": false+ }+ }+ ],+ "components": {+ "agents": [+ {+ "provider": "autogen_agentchat.agents.AssistantAgent",+ "component_type": "agent",+ "version": 1,+ "component_version": 1,+ "description": "An agent that provides assistance with tool use.",+ "label": "AssistantAgent",+ "config": {+ "name": "assistant_agent",+ "model_client": {+ "provider": "autogen_ext.models.openai.OpenAIChatCompletionClient",+ "component_type": "model",+ "version": 1,+ "component_version": 1,+ "description": "Chat completion client for OpenAI hosted models.",+ "label": "OpenAIChatCompletionClient",+ "config": {+ "model": "gpt-4o-mini"+ }+ },+ "tools": [+ {+ "provider": "autogen_core.tools.FunctionTool",+ "component_type": "tool",+ "version": 1,+ "component_version": 1,+ "description": "Create custom tools by wrapping standard Python functions.",+ "label": "FunctionTool",+ "config": {+ "source_code": "def calculator(a: float, b: float, operator: str) -> str:\n try:\n if operator == '+':\n return str(a + b)\n elif operator == '-':\n return str(a - b)\n elif operator == '*':\n return str(a * b)\n elif operator == '/':\n if b == 0:\n return 'Error: Division by zero'\n return str(a / b)\n else:\n return 'Error: Invalid operator. Please use +, -, *, or /'\n except Exception as e:\n return f'Error: {str(e)}'\n",+ "name": "calculator",+ "description": "A simple calculator that performs basic arithmetic operations",+ "global_imports": [],+ "has_cancellation_support": false+ }+ }+ ],+ "handoffs": [],+ "model_context": {+ "provider": "autogen_core.model_context.UnboundedChatCompletionContext",+ "component_type": "chat_completion_context",+ "version": 1,+ "component_version": 1,+ "description": "An unbounded chat completion context that keeps a view of the all the messages.",+ "label": "UnboundedChatCompletionContext",+ "config": {}+ },+ "description": "An agent that provides assistance with ability to use tools.",+ "system_message": "You are a helpful assistant. Solve tasks carefully. When done, say TERMINATE.",+ "model_client_stream": false,+ "reflect_on_tool_use": false,+ "tool_call_summary_format": "{result}"+ }+ },+ {+ "provider": "autogen_ext.agents.web_surfer.MultimodalWebSurfer",+ "component_type": "agent",+ "version": 1,+ "component_version": 1,+ "description": "MultimodalWebSurfer is a multimodal agent that acts as a web surfer that can search the web and visit web pages.",+ "label": "MultimodalWebSurfer",+ "config": {+ "name": "websurfer_agent",+ "model_client": {+ "provider": "autogen_ext.models.openai.OpenAIChatCompletionClient",+ "component_type": "model",+ "version": 1,+ "component_version": 1,+ "description": "Chat completion client for OpenAI hosted models.",+ "label": "OpenAIChatCompletionClient",+ "config": {+ "model": "gpt-4o-mini"+ }+ },+ "description": "an agent that solves tasks by browsing the web",+ "headless": true,+ "start_page": "https://www.bing.com/",+ "animate_actions": false,+ "to_save_screenshots": false,+ "use_ocr": false,+ "to_resize_viewport": true+ }+ },+ {+ "provider": "autogen_agentchat.agents.AssistantAgent",+ "component_type": "agent",+ "version": 1,+ "component_version": 1,+ "description": "An agent that provides assistance with tool use.",+ "label": "AssistantAgent",+ "config": {+ "name": "assistant_agent",+ "model_client": {+ "provider": "autogen_ext.models.openai.OpenAIChatCompletionClient",+ "component_type": "model",+ "version": 1,+ "component_version": 1,+ "description": "Chat completion client for OpenAI hosted models.",+ "label": "OpenAIChatCompletionClient",+ "config": {+ "model": "gpt-4o-mini"+ }+ },+ "tools": [],+ "handoffs": [],+ "model_context": {+ "provider": "autogen_core.model_context.UnboundedChatCompletionContext",+ "component_type": "chat_completion_context",+ "version": 1,+ "component_version": 1,+ "description": "An unbounded chat completion context that keeps a view of the all the messages.",+ "label": "UnboundedChatCompletionContext",+ "config": {}+ },+ "description": "an agent that verifies and summarizes information",+ "system_message": "You are a task verification assistant who is working with a web surfer agent to solve tasks. At each point, check if the task has been completed as requested by the user. If the websurfer_agent responds and the task has not yet been completed, respond with what is left to do and then say 'keep going'. If and only when the task has been completed, summarize and present a final answer that directly addresses the user task in detail and then respond with TERMINATE.",+ "model_client_stream": false,+ "reflect_on_tool_use": false,+ "tool_call_summary_format": "{result}"+ }+ },+ {+ "provider": "autogen_agentchat.agents.UserProxyAgent",+ "component_type": "agent",+ "version": 1,+ "component_version": 1,+ "description": "An agent that can represent a human user through an input function.",+ "label": "UserProxyAgent",+ "config": {+ "name": "user_proxy",+ "description": "a human user that should be consulted only when the assistant_agent is unable to verify the information provided by the websurfer_agent"+ }+ }+ ],+ "models": [+ {+ "provider": "autogen_ext.models.openai.OpenAIChatCompletionClient",+ "component_type": "model",+ "version": 1,+ "component_version": 1,+ "description": "Chat completion client for OpenAI hosted models.",+ "label": "OpenAIChatCompletionClient",+ "config": {+ "model": "gpt-4o-mini"+ }+ },+ {+ "provider": "autogen_ext.models.openai.OpenAIChatCompletionClient",+ "component_type": "model",+ "version": 1,+ "component_version": 1,+ "description": "Example on how to use the OpenAIChatCopletionClient with local models (Ollama, vllm etc).",+ "label": "Mistral-7B vllm",+ "config": {+ "model": "TheBloke/Mistral-7B-Instruct-v0.2-GGUF",+ "base_url": "http://localhost:1234/v1"+ }+ },+ {+ "provider": "autogen_ext.models.openai.OpenAIChatCompletionClient",+ "component_type": "model",+ "version": 1,+ "component_version": 1,+ "description": "Chat completion client for OpenAI hosted models.",+ "label": "OpenAIChatCompletionClient",+ "config": {+ "model": "gpt-4o-mini"+ }+ }+ ],+ "tools": [+ {+ "provider": "autogen_core.tools.FunctionTool",+ "component_type": "tool",+ "version": 1,+ "component_version": 1,+ "description": "Create custom tools by wrapping standard Python functions.",+ "label": "FunctionTool",+ "config": {+ "source_code": "def calculator(a: float, b: float, operator: str) -> str:\n try:\n if operator == '+':\n return str(a + b)\n elif operator == '-':\n return str(a - b)\n elif operator == '*':\n return str(a * b)\n elif operator == '/':\n if b == 0:\n return 'Error: Division by zero'\n return str(a / b)\n else:\n return 'Error: Invalid operator. Please use +, -, *, or /'\n except Exception as e:\n return f'Error: {str(e)}'\n",+ "name": "calculator",+ "description": "A simple calculator that performs basic arithmetic operations",+ "global_imports": [],+ "has_cancellation_support": false+ }+ }+ ],+ "terminations": [+ {+ "provider": "autogen_agentchat.conditions.TextMentionTermination",+ "component_type": "termination",+ "version": 1,+ "component_version": 1,+ "description": "Terminate the conversation if a specific text is mentioned.",+ "label": "TextMentionTermination",+ "config": {+ "text": "TERMINATE"+ }+ },+ {+ "provider": "autogen_agentchat.conditions.MaxMessageTermination",+ "component_type": "termination",+ "version": 1,+ "component_version": 1,+ "description": "Terminate the conversation after a maximum number of messages have been exchanged.",+ "label": "MaxMessageTermination",+ "config": {+ "max_messages": 10+ }+ },+ {+ "provider": "autogen_agentchat.base.OrTerminationCondition",+ "component_type": "termination",+ "version": 1,+ "component_version": 1,+ "description": null,+ "label": "OrTerminationCondition",+ "config": {+ "conditions": [+ {+ "provider": "autogen_agentchat.conditions.TextMentionTermination",+ "component_type": "termination",+ "version": 1,+ "component_version": 1,+ "description": "Terminate the conversation if a specific text is mentioned.",+ "label": "TextMentionTermination",+ "config": {+ "text": "TERMINATE"+ }+ },+ {+ "provider": "autogen_agentchat.conditions.MaxMessageTermination",+ "component_type": "termination",+ "version": 1,+ "component_version": 1,+ "description": "Terminate the conversation after a maximum number of messages have been exchanged.",+ "label": "MaxMessageTermination",+ "config": {+ "max_messages": 10+ }+ }+ ]+ }+ },+ {+ "provider": "autogen_agentchat.base.OrTerminationCondition",+ "component_type": "termination",+ "version": 1,+ "component_version": 1,+ "description": null,+ "label": "OrTerminationCondition",+ "config": {+ "conditions": [+ {+ "provider": "autogen_agentchat.conditions.MaxMessageTermination",+ "component_type": "termination",+ "version": 1,+ "component_version": 1,+ "description": "Terminate the conversation after a maximum number of messages have been exchanged.",+ "label": "MaxMessageTermination",+ "config": {+ "max_messages": 20+ }+ },+ {+ "provider": "autogen_agentchat.conditions.TextMentionTermination",+ "component_type": "termination",+ "version": 1,+ "component_version": 1,+ "description": "Terminate the conversation if a specific text is mentioned.",+ "label": "TextMentionTermination",+ "config": {+ "text": "TERMINATE"+ }+ }+ ]+ }+ }+ ]+ }+ }+}diff --git a/python/packages/autogen-studio/frontend/src/components/views/gallery/detail.tsx b/python/packages/autogen-studio/frontend/src/components/views/gallery/detail.tsxindex 00e9fe331..0eb23391f 100644--- a/python/packages/autogen-studio/frontend/src/components/views/gallery/detail.tsx+++ b/python/packages/autogen-studio/frontend/src/components/views/gallery/detail.tsx@@ -19,13 +19,13 @@ import {import type { Gallery } from "./types";import { useGalleryStore } from "./store";import { MonacoEditor } from "../monaco";-import { ComponentConfigTypes } from "../../types/datamodel";import { getRelativeTimeString, TruncatableText } from "../atoms";+import { Component, ComponentConfig } from "../../types/datamodel";const ComponentGrid: React.FC<{title: string;icon: React.ReactNode;- items: ComponentConfigTypes[];+ items: Component<ComponentConfig>[];}> = ({ title, icon, items }) => {const [isExpanded, setIsExpanded] = useState(true);@@ -58,16 +58,17 @@ const ComponentGrid: React.FC<{key={idx}className="bg-secondary rounded p-3 hover:bg-tertiary transition-colors">- <div className="text-sm font-medium truncate">- {item.component_type}+ <div className="text-xs break-all text-secondary my-1 mb-2">+ {item.provider}</div>+ <div className="text-sm font-medium truncate">{item.label}</div>{item.description && (- <p className="text-xs text-primary mt-1 ">+ <div className="text-xs text-primary mt-1 "><TruncatableTextcontent={item.description}textThreshold={150}/>- </p>+ </div>)}</div>))}diff --git a/python/packages/autogen-studio/frontend/src/components/views/gallery/store.tsx b/python/packages/autogen-studio/frontend/src/components/views/gallery/store.tsxindex c09096f73..5cd2ffdfb 100644--- a/python/packages/autogen-studio/frontend/src/components/views/gallery/store.tsx+++ b/python/packages/autogen-studio/frontend/src/components/views/gallery/store.tsx@@ -3,6 +3,7 @@ import { persist } from "zustand/middleware";import { Gallery } from "./types";import {AgentConfig,+ Component,ModelConfig,TeamConfig,TerminationConfig,@@ -25,12 +26,12 @@ interface GalleryStore {syncGallery: (id: string) => Promise<void>;getLastSyncTime: (id: string) => string | null;getGalleryComponents: () => {- teams: TeamConfig[];+ teams: Component<TeamConfig>[];components: {- agents: AgentConfig[];- models: ModelConfig[];- tools: ToolConfig[];- terminations: TerminationConfig[];+ agents: Component<AgentConfig>[];+ models: Component<ModelConfig>[];+ tools: Component<ToolConfig>[];+ terminations: Component<TerminationConfig>[];};};}@@ -150,7 +151,7 @@ export const useGalleryStore = create<GalleryStore>()(},}),{- name: "gallery-storage",+ name: "gallery-storage-v1",}));diff --git a/python/packages/autogen-studio/frontend/src/components/views/gallery/types.ts b/python/packages/autogen-studio/frontend/src/components/views/gallery/types.tsindex 015eb961c..7db306b90 100644--- a/python/packages/autogen-studio/frontend/src/components/views/gallery/types.ts+++ b/python/packages/autogen-studio/frontend/src/components/views/gallery/types.ts@@ -1,5 +1,6 @@import {AgentConfig,+ Component,ModelConfig,TeamConfig,TerminationConfig,@@ -25,12 +26,12 @@ export interface Gallery {url?: string;metadata: GalleryMetadata;items: {- teams: TeamConfig[];+ teams: Component<TeamConfig>[];components: {- agents: AgentConfig[];- models: ModelConfig[];- tools: ToolConfig[];- terminations: TerminationConfig[];+ agents: Component<AgentConfig>[];+ models: Component<ModelConfig>[];+ tools: Component<ToolConfig>[];+ terminations: Component<TerminationConfig>[];};};}diff --git a/python/packages/autogen-studio/frontend/src/components/views/gallery/utils.ts b/python/packages/autogen-studio/frontend/src/components/views/gallery/utils.tsindex 2b0e4ea83..d8dc75bc1 100644--- a/python/packages/autogen-studio/frontend/src/components/views/gallery/utils.ts+++ b/python/packages/autogen-studio/frontend/src/components/views/gallery/utils.ts@@ -1,194 +1,15 @@-import {- AssistantAgentConfig,- CombinationTerminationConfig,- MaxMessageTerminationConfig,- OpenAIModelConfig,- PythonFunctionToolConfig,- RoundRobinGroupChatConfig,- TextMentionTerminationConfig,- UserProxyAgentConfig,-} from "../../types/datamodel";+import { Gallery } from "./types";-export const defaultGallery = {- id: "gallery_default",- name: "Default Component Gallery",- metadata: {- author: "AutoGen Team",- created_at: "2024-12-12T00:00:00Z",- updated_at: "2024-12-12T00:00:00Z",- version: "1.0.0",- description:- "A default gallery containing basic components for human-in-loop conversations",- tags: ["human-in-loop", "assistant"],- license: "MIT",- category: "conversation",- },- items: {- teams: [- {- component_type: "team",- description:- "A team with an assistant agent and a user agent to enable human-in-loop task completion in a round-robin fashion",- name: "huma_in_loop_team",- participants: [- {- component_type: "agent",- description:- "An assistant agent that can help users complete tasks",- name: "assistant_agent",- agent_type: "AssistantAgent",- system_message:- "You are a helpful assistant. Solve tasks carefully. You also have a calculator tool which you can use if needed. When the task is done respond with TERMINATE.",- model_client: {- component_type: "model",- description: "A GPT-4o mini model",- model: "gpt-4o-mini",- model_type: "OpenAIChatCompletionClient",- },- tools: [- {- component_type: "tool",- name: "calculator",- description:- "A simple calculator that performs basic arithmetic operations between two numbers",- content:- "def calculator(a: float, b: float, operator: str) -> str:\n try:\n if operator == '+':\n return str(a + b)\n elif operator == '-':\n return str(a - b)\n elif operator == '*':\n return str(a * b)\n elif operator == '/':\n if b == 0:\n return 'Error: Division by zero'\n return str(a / b)\n else:\n return 'Error: Invalid operator. Please use +, -, *, or /'\n except Exception as e:\n return f'Error: {str(e)}'",- tool_type: "PythonFunction",- },- ],- },- {- component_type: "agent",- description: "A user agent that is driven by a human user",- name: "user_agent",- agent_type: "UserProxyAgent",- tools: [],- },- ],- team_type: "RoundRobinGroupChat",- termination_condition: {- description:- "Terminate the conversation when the user mentions 'TERMINATE' or after 10 messages",- component_type: "termination",- termination_type: "CombinationTermination",- operator: "or",- conditions: [- {- component_type: "termination",- description:- "Terminate the conversation when the user mentions 'TERMINATE'",- termination_type: "TextMentionTermination",- text: "TERMINATE",- },- {- component_type: "termination",- description: "Terminate the conversation after 10 messages",- termination_type: "MaxMessageTermination",- max_messages: 10,- },- ],- },- } as RoundRobinGroupChatConfig,- ],- components: {- agents: [- {- component_type: "agent",- description: "An assistant agent that can help users complete tasks",- name: "assistant_agent",- agent_type: "AssistantAgent",- system_message:- "You are a helpful assistant. Solve tasks carefully. You also have a calculator tool which you can use if needed. When the task is done respond with TERMINATE.",- model_client: {- component_type: "model",- description: "A GPT-4o mini model",- model: "gpt-4o-mini",- model_type: "OpenAIChatCompletionClient",- },- tools: [- {- component_type: "tool",- name: "calculator",- description:- "A simple calculator that performs basic arithmetic operations between two numbers",- content:- "def calculator(a: float, b: float, operator: str) -> str:\n try:\n if operator == '+':\n return str(a + b)\n elif operator == '-':\n return str(a - b)\n elif operator == '*':\n return str(a * b)\n elif operator == '/':\n if b == 0:\n return 'Error: Division by zero'\n return str(a / b)\n else:\n return 'Error: Invalid operator. Please use +, -, *, or /'\n except Exception as e:\n return f'Error: {str(e)}'",- tool_type: "PythonFunction",- },- ],- } as AssistantAgentConfig,- {- component_type: "agent",- description: "A user agent that is driven by a human user",- name: "user_agent",- agent_type: "UserProxyAgent",- tools: [],- } as UserProxyAgentConfig,- ],- models: [- {- component_type: "model",- description: "A GPT-4o mini model",- model: "gpt-4o-mini",- model_type: "OpenAIChatCompletionClient",- } as OpenAIModelConfig,- ],- tools: [- {- component_type: "tool",- name: "calculator",- description:- "A simple calculator that performs basic arithmetic operations between two numbers",- content:- "def calculator(a: float, b: float, operator: str) -> str:\n try:\n if operator == '+':\n return str(a + b)\n elif operator == '-':\n return str(a - b)\n elif operator == '*':\n return str(a * b)\n elif operator == '/':\n if b == 0:\n return 'Error: Division by zero'\n return str(a / b)\n else:\n return 'Error: Invalid operator. Please use +, -, *, or /'\n except Exception as e:\n return f'Error: {str(e)}'",- tool_type: "PythonFunction",- } as PythonFunctionToolConfig,- {- component_type: "tool",- name: "fetch_website",- description: "Fetch and return the content of a website URL",- content:- "async def fetch_website(url: str) -> str:\n try:\n import requests\n from urllib.parse import urlparse\n \n # Validate URL format\n parsed = urlparse(url)\n if not parsed.scheme or not parsed.netloc:\n return \"Error: Invalid URL format. Please include http:// or https://\"\n \n # Add scheme if not present\n if not url.startswith(('http://', 'https://')): \n url = 'https://' + url\n \n # Set headers to mimic a browser request\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'\n }\n \n # Make the request with a timeout\n response = requests.get(url, headers=headers, timeout=10)\n response.raise_for_status()\n \n # Return the text content\n return response.text\n \n except requests.exceptions.Timeout:\n return \"Error: Request timed out\"\n except requests.exceptions.ConnectionError:\n return \"Error: Failed to connect to the website\"\n except requests.exceptions.HTTPError as e:\n return f\"Error: HTTP {e.response.status_code} - {e.response.reason}\"\n except Exception as e:\n return f\"Error: {str(e)}\"",- tool_type: "PythonFunction",- } as PythonFunctionToolConfig,- ],- terminations: [- {- component_type: "termination",- description:- "Terminate the conversation when the user mentions 'TERMINATE'",- termination_type: "TextMentionTermination",- text: "TERMINATE",- } as TextMentionTerminationConfig,- {- component_type: "termination",- description: "Terminate the conversation after 10 messages",- termination_type: "MaxMessageTermination",- max_messages: 10,- } as MaxMessageTerminationConfig,- {- component_type: "termination",- description:- "Terminate the conversation when the user mentions 'TERMINATE' or after 10 messages",- termination_type: "CombinationTermination",- operator: "or",- conditions: [- {- component_type: "termination",- description:- "Terminate the conversation when the user mentions 'TERMINATE'",- termination_type: "TextMentionTermination",- text: "TERMINATE",- },- {- component_type: "termination",- description: "Terminate the conversation after 10 messages",- termination_type: "MaxMessageTermination",- max_messages: 10,- },- ],- } as CombinationTerminationConfig,- ],- },- },+// Load and parse the gallery JSON file+const loadGalleryFromJson = (): Gallery => {+ try {+ // You can adjust the path to your JSON file as needed+ const galleryJson = require("./default_gallery.json");+ return galleryJson as Gallery;+ } catch (error) {+ console.error("Error loading gallery JSON:", error);+ throw error;+ }};++export const defaultGallery: Gallery = loadGalleryFromJson();diff --git a/python/packages/autogen-studio/frontend/src/components/views/session/chat/agentflow/agentflow.tsx b/python/packages/autogen-studio/frontend/src/components/views/session/chat/agentflow/agentflow.tsxindex 9b18038c6..e569b517a 100644--- a/python/packages/autogen-studio/frontend/src/components/views/session/chat/agentflow/agentflow.tsx+++ b/python/packages/autogen-studio/frontend/src/components/views/session/chat/agentflow/agentflow.tsx@@ -25,6 +25,7 @@ import {AgentConfig,TeamConfig,Run,+ Component,} from "../../../../types/datamodel";import { CustomEdge, CustomEdgeData } from "./edge";import { useConfigStore } from "../../../../../hooks/store";@@ -32,7 +33,7 @@ import { AgentFlowToolbar } from "./toolbar";import { EdgeMessageModal } from "./edgemessagemodal";interface AgentFlowProps {- teamConfig: TeamConfig;+ teamConfig: Component<TeamConfig>;run: Run;}@@ -151,7 +152,7 @@ const getLayoutedElements = (const createNode = (id: string,type: "user" | "agent" | "end",- agentConfig?: AgentConfig,+ agentConfig?: Component<AgentConfig>,isActive: boolean = false,run?: Run): Node => {@@ -218,7 +219,7 @@ const createNode = (data: {type: "agent",label: id,- agentType: agentConfig?.agent_type || "",+ agentType: agentConfig?.label || "",description: agentConfig?.description || "",isActive,status: "",@@ -281,8 +282,8 @@ const AgentFlow: React.FC<AgentFlowProps> = ({ teamConfig, run }) => {// Add first message node if it existsif (messages.length > 0) {- const firstAgentConfig = teamConfig.participants.find(- (p) => p.name === messages[0].source+ const firstAgentConfig = teamConfig.config.participants.find(+ (p) => p.config.name === messages[0].source);nodeMap.set(messages[0].source,@@ -322,8 +323,8 @@ const AgentFlow: React.FC<AgentFlowProps> = ({ teamConfig, run }) => {}if (!nodeMap.has(nextMsg.source)) {- const agentConfig = teamConfig.participants.find(- (p) => p.name === nextMsg.source+ const agentConfig = teamConfig.config.participants.find(+ (p) => p.config.name === nextMsg.source);nodeMap.set(nextMsg.source,@@ -479,7 +480,7 @@ const AgentFlow: React.FC<AgentFlowProps> = ({ teamConfig, run }) => {return { nodes: Array.from(nodeMap.values()), edges: newEdges };},- [teamConfig.participants, run, settings]+ [teamConfig.config.participants, run, settings]);const handleToggleFullscreen = useCallback(() => {diff --git a/python/packages/autogen-studio/frontend/src/components/views/session/chat/chat.tsx b/python/packages/autogen-studio/frontend/src/components/views/session/chat/chat.tsxindex 65d9452bb..8f5ea8bcd 100644--- a/python/packages/autogen-studio/frontend/src/components/views/session/chat/chat.tsx+++ b/python/packages/autogen-studio/frontend/src/components/views/session/chat/chat.tsx@@ -11,6 +11,7 @@ import {RunStatus,TeamResult,Session,+ Component,} from "../../../types/datamodel";import { appContext } from "../../../../hooks/provider";import ChatInput from "./chatinput";@@ -46,7 +47,8 @@ export default function ChatView({ session }: ChatViewProps) {const [activeSocket, setActiveSocket] = React.useState<WebSocket | null>(null);- const [teamConfig, setTeamConfig] = React.useState<TeamConfig | null>(null);+ const [teamConfig, setTeamConfig] =+ React.useState<Component<TeamConfig> | null>(null);const inputTimeoutRef = React.useRef<NodeJS.Timeout | null>(null);const activeSocketRef = React.useRef<WebSocket | null>(null);@@ -94,7 +96,7 @@ export default function ChatView({ session }: ChatViewProps) {teamAPI.getTeam(session.team_id, user.email).then((team) => {- setTeamConfig(team.config);+ setTeamConfig(team.component);}).catch((error) => {console.error("Error loading team config:", error);diff --git a/python/packages/autogen-studio/frontend/src/components/views/session/chat/runview.tsx b/python/packages/autogen-studio/frontend/src/components/views/session/chat/runview.tsxindex 57557ec15..73afef90e 100644--- a/python/packages/autogen-studio/frontend/src/components/views/session/chat/runview.tsx+++ b/python/packages/autogen-studio/frontend/src/components/views/session/chat/runview.tsx@@ -11,7 +11,7 @@ import {ChevronUp,Bot,} from "lucide-react";-import { Run, Message, TeamConfig } from "../../../types/datamodel";+import { Run, Message, TeamConfig, Component } from "../../../types/datamodel";import AgentFlow from "./agentflow/agentflow";import { RenderMessage } from "./rendermessage";import InputRequestView from "./inputrequest";@@ -24,7 +24,7 @@ import {interface RunViewProps {run: Run;- teamConfig?: TeamConfig;+ teamConfig?: Component<TeamConfig>;onInputResponse?: (response: string) => void;onCancel?: () => void;isFirstRun?: boolean;@@ -54,6 +54,7 @@ const RunView: React.FC<RunViewProps> = ({}, [run.messages]); // Only depend on messages changingconst calculateThreadTokens = (messages: Message[]) => {+ // console.log("messages", messages);return messages.reduce((total, msg) => {if (!msg.config.models_usage) return total;return (diff --git a/python/packages/autogen-studio/frontend/src/components/views/session/editor.tsx b/python/packages/autogen-studio/frontend/src/components/views/session/editor.tsxindex c83586955..c89ee39a7 100644--- a/python/packages/autogen-studio/frontend/src/components/views/session/editor.tsx+++ b/python/packages/autogen-studio/frontend/src/components/views/session/editor.tsx@@ -132,7 +132,7 @@ export const SessionEditor: React.FC<SessionEditorProps> = ({}options={teams.map((team) => ({value: team.id,- label: `${team.config.name} (${team.config.team_type})`,+ label: `${team.component.label} (${team.component.component_type})`,}))}notFoundContent={loading ? <Spin size="small" /> : null}/>diff --git a/python/packages/autogen-studio/frontend/src/components/views/team/builder/builder.tsx b/python/packages/autogen-studio/frontend/src/components/views/team/builder/builder.tsxindex 6abcb4cfc..d0e5f3dd3 100644--- a/python/packages/autogen-studio/frontend/src/components/views/team/builder/builder.tsx+++ b/python/packages/autogen-studio/frontend/src/components/views/team/builder/builder.tsx@@ -1,4 +1,5 @@-import React, { useCallback, useRef, useState } from "react";+//team/builder/builder.tsx+import React, { useCallback, useEffect, useRef, useState } from "react";import {DndContext,useSensor,@@ -29,7 +30,8 @@ import { edgeTypes, nodeTypes } from "./nodes";import "./builder.css";import TeamBuilderToolbar from "./toolbar";import { MonacoEditor } from "../../monaco";-import { NodeEditor } from "./node-editor";+import { NodeEditor } from "./node-editor/node-editor";+import debounce from "lodash.debounce";const { Sider, Content } = Layout;@@ -66,6 +68,7 @@ export const TeamBuilder: React.FC<TeamBuilderProps> = ({history,updateNode,selectedNodeId,+ setSelectedNode,} = useTeamBuilderStore();const currentHistoryIndex = useTeamBuilderStore(@@ -113,9 +116,9 @@ export const TeamBuilder: React.FC<TeamBuilderProps> = ({// Load initial configReact.useEffect(() => {- if (team?.config) {+ if (team?.component) {const { nodes: initialNodes, edges: initialEdges } = loadFromJson(- team.config+ team.component);setNodes(initialNodes);setEdges(initialEdges);@@ -124,36 +127,45 @@ export const TeamBuilder: React.FC<TeamBuilderProps> = ({// Handle JSON changesconst handleJsonChange = useCallback(- (value: string) => {+ debounce((value: string) => {try {const config = JSON.parse(value);- loadFromJson(config);- // dirty ?+ // Always consider JSON edits as changes that should affect isDirty state+ loadFromJson(config, false);+ // Force history update even if nodes/edges appear same+ useTeamBuilderStore.getState().addToHistory();} catch (error) {console.error("Invalid JSON:", error);}- },+ }, 1000),[loadFromJson]);+ // Cleanup debounced function+ useEffect(() => {+ return () => {+ handleJsonChange.cancel();+ };+ }, [handleJsonChange]);+// Handle saveconst handleSave = useCallback(async () => {try {- const config = syncToJson();- if (!config) {+ const component = syncToJson();+ if (!component) {throw new Error("Unable to generate valid configuration");}if (onChange) {- console.log("Saving team configuration", config);+ console.log("Saving team configuration", component);const teamData: Partial<Team> = team? {...team,- config,+ component,created_at: undefined,updated_at: undefined,}- : { config };+ : { component };await onChange(teamData);resetHistory();}@@ -212,7 +224,10 @@ export const TeamBuilder: React.FC<TeamBuilderProps> = ({const targetNode = nodes.find((node) => node.id === over.id);if (!targetNode) return;- const isValid = validateDropTarget(draggedType, targetNode.data.type);+ const isValid = validateDropTarget(+ draggedType,+ targetNode.data.component.component_type+ );// Add visual feedback class to target nodeif (isValid) {targetNode.className = "drop-target-valid";@@ -228,14 +243,16 @@ export const TeamBuilder: React.FC<TeamBuilderProps> = ({const draggedItem = active.data.current.current;const dropZoneId = over.id as string;- const [nodeId, zoneType] = dropZoneId.split("-zone")[0].split("-");-+ const [nodeId] = dropZoneId.split("@@@");// Find target nodeconst targetNode = nodes.find((node) => node.id === nodeId);if (!targetNode) return;// Validate drop- const isValid = validateDropTarget(draggedItem.type, targetNode.data.type);+ const isValid = validateDropTarget(+ draggedItem.type,+ targetNode.data.component.component_type+ );if (!isValid) return;const position = {@@ -244,12 +261,7 @@ export const TeamBuilder: React.FC<TeamBuilderProps> = ({};// Pass both new node data AND target node id- addNode(- draggedItem.type as ComponentTypes,- position,- draggedItem.config,- nodeId- );+ addNode(position, draggedItem.config, nodeId);};const onDragStart = (item: DragItem) => {@@ -408,6 +420,7 @@ export const TeamBuilder: React.FC<TeamBuilderProps> = ({handleSave();}}}+ onClose={() => setSelectedNode(null)}/></Layout></DndContext>diff --git a/python/packages/autogen-studio/frontend/src/components/views/team/builder/library.tsx b/python/packages/autogen-studio/frontend/src/components/views/team/builder/library.tsxindex c5bdfceb1..34118174e 100644--- a/python/packages/autogen-studio/frontend/src/components/views/team/builder/library.tsx+++ b/python/packages/autogen-studio/frontend/src/components/views/team/builder/library.tsx@@ -10,22 +10,16 @@ import {Timer,Maximize2,Minimize2,+ GripVertical,} from "lucide-react";-import type {- AgentConfig,- ModelConfig,- TerminationConfig,- ToolConfig,-} from "../../../types/datamodel";import Sider from "antd/es/layout/Sider";import { useGalleryStore } from "../../gallery/store";+import { ComponentTypes } from "../../../types/datamodel";interface ComponentConfigTypes {[key: string]: any;}-type ComponentTypes = "agent" | "model" | "tool" | "termination";-interface LibraryProps {}interface PresetItemProps {@@ -66,11 +60,12 @@ const PresetItem: React.FC<PresetItemProps> = ({style={style}{...attributes}{...listeners}- className="p-2 text-primary mb-2 border border-secondary rounded cursor-move hover:bg-secondary transition-colors"+ className="p-2 text-primary mb-2 border border-secondary rounded cursor-move hover:bg-secondary transition-colors "><div className="flex items-center gap-2">+ <GripVertical className="w-4 h-4 inline-block" />{icon}- <span>{label}</span>+ <span className=" text-sm">{label}</span></div></div>);@@ -91,7 +86,7 @@ export const ComponentLibrary: React.FC<LibraryProps> = () => {title: "Agents",type: "agent" as ComponentTypes,items: defaultGallery.items.components.agents.map((agent) => ({- label: agent.name,+ label: agent.label,config: agent,})),icon: <Bot className="w-4 h-4" />,@@ -100,7 +95,7 @@ export const ComponentLibrary: React.FC<LibraryProps> = () => {title: "Models",type: "model" as ComponentTypes,items: defaultGallery.items.components.models.map((model) => ({- label: `${model.model_type} - ${model.model}`,+ label: `${model.component_type} - ${model.config.model}`,config: model,})),icon: <Brain className="w-4 h-4" />,@@ -109,7 +104,7 @@ export const ComponentLibrary: React.FC<LibraryProps> = () => {title: "Tools",type: "tool" as ComponentTypes,items: defaultGallery.items.components.tools.map((tool) => ({- label: tool.name,+ label: tool.config.name,config: tool,})),icon: <Wrench className="w-4 h-4" />,@@ -119,7 +114,7 @@ export const ComponentLibrary: React.FC<LibraryProps> = () => {type: "termination" as ComponentTypes,items: defaultGallery.items.components.terminations.map((termination) => ({- label: `${termination.termination_type}`,+ label: `${termination.label}`,config: termination,})),@@ -131,7 +126,7 @@ export const ComponentLibrary: React.FC<LibraryProps> = () => {const items: CollapseProps["items"] = sections.map((section) => {const filteredItems = section.items.filter((item) =>- item.label.toLowerCase().includes(searchTerm.toLowerCase())+ item.label?.toLowerCase().includes(searchTerm.toLowerCase()));return {@@ -153,7 +148,7 @@ export const ComponentLibrary: React.FC<LibraryProps> = () => {id={`${section.title.toLowerCase()}-${itemIndex}`}type={section.type}config={item.config}- label={item.label}+ label={item.label || ""}icon={section.icon}/>))}diff --git a/python/packages/autogen-studio/frontend/src/components/views/team/builder/node-editor.tsx b/python/packages/autogen-studio/frontend/src/components/views/team/builder/node-editor.tsxdeleted file mode 100644index 07520e47a..000000000--- a/python/packages/autogen-studio/frontend/src/components/views/team/builder/node-editor.tsx+++ /dev/null@@ -1,665 +0,0 @@-import React, { useEffect, useState } from "react";-import { Drawer, Button, Space, message, Select, Input } from "antd";-import { NodeEditorProps } from "./types";-import { useTeamBuilderStore } from "./store";-import {- TeamConfig,- ComponentTypes,- TeamTypes,- ModelTypes,- SelectorGroupChatConfig,- RoundRobinGroupChatConfig,- ModelConfig,- AzureOpenAIModelConfig,- OpenAIModelConfig,- ComponentConfigTypes,- AgentConfig,- ToolConfig,- AgentTypes,- ToolTypes,- TerminationConfig,- TerminationTypes,- MaxMessageTerminationConfig,- TextMentionTerminationConfig,- CombinationTerminationConfig,-} from "../../../types/datamodel";--const { TextArea } = Input;--interface EditorProps<T> {- value: T;- onChange: (value: T) => void;- disabled?: boolean;-}--const TeamEditor: React.FC<EditorProps<TeamConfig>> = ({- value,- onChange,- disabled,-}) => {- const handleTypeChange = (teamType: TeamTypes) => {- if (teamType === "SelectorGroupChat") {- onChange({- ...value,- team_type: teamType,- selector_prompt: "",- model_client: {- component_type: "model",- model: "",- model_type: "OpenAIChatCompletionClient",- },- } as SelectorGroupChatConfig);- } else {- const { selector_prompt, model_client, ...rest } =- value as SelectorGroupChatConfig;- onChange({- ...rest,- team_type: teamType,- } as RoundRobinGroupChatConfig);- }- };-- return (- <Space direction="vertical" size="large" style={{ width: "100%" }}>- <div>- <label className="block text-sm font-medium mb-2">Team Type</label>- <Select- value={value.team_type}- onChange={handleTypeChange}- disabled={disabled}- style={{ width: "100%" }}- options={[- { value: "RoundRobinGroupChat", label: "Round Robin" },- { value: "SelectorGroupChat", label: "Selector" },- ]}- />- </div>-- <div>- <label className="block text-sm font-medium mb-2">Name</label>- <Input- value={value.name}- onChange={(e) => onChange({ ...value, name: e.target.value })}- disabled={disabled}- />- </div>-- {value.team_type === "SelectorGroupChat" && (- <>- <div>- <label className="block text-sm font-medium mb-2">- Selector Prompt- </label>- <TextArea- value={(value as SelectorGroupChatConfig).selector_prompt}- onChange={(e) =>- onChange({- ...value,- selector_prompt: e.target.value,- } as SelectorGroupChatConfig)- }- disabled={disabled}- rows={4}- />- </div>-- <ModelEditor- value={(value as SelectorGroupChatConfig).model_client}- onChange={(modelConfig) =>- onChange({- ...value,- model_client: modelConfig,- } as SelectorGroupChatConfig)- }- disabled={disabled}- />- </>- )}- </Space>- );-};--const ModelEditor: React.FC<EditorProps<ModelConfig>> = ({- value,- onChange,- disabled,-}) => {- const handleTypeChange = (modelType: ModelTypes) => {- if (modelType === "AzureOpenAIChatCompletionClient") {- onChange({- ...value,- model_type: modelType,- azure_deployment: "",- api_version: "",- azure_endpoint: "",- azure_ad_token_provider: "",- } as AzureOpenAIModelConfig);- } else {- const {- azure_deployment,- api_version,- azure_endpoint,- azure_ad_token_provider,- ...rest- } = value as AzureOpenAIModelConfig;- onChange({- ...rest,- model_type: modelType,- } as OpenAIModelConfig);- }- };-- return (- <Space direction="vertical" size="large" style={{ width: "100%" }}>- <div>- <label className="block text-sm font-medium mb-2">Model Type</label>- <Select- value={value.model_type}- onChange={handleTypeChange}- disabled={disabled}- style={{ width: "100%" }}- options={[- { value: "OpenAIChatCompletionClient", label: "OpenAI" },- { value: "AzureOpenAIChatCompletionClient", label: "Azure OpenAI" },- ]}- />- </div>-- <div>- <label className="block text-sm font-medium mb-2">Model</label>- <Input- value={value.model}- onChange={(e) => onChange({ ...value, model: e.target.value })}- disabled={disabled}- />- </div>-- {value.model_type === "OpenAIChatCompletionClient" && (- <div>- <label className="block text-sm font-medium mb-2">API Key</label>- <Input.Password- value={(value as OpenAIModelConfig).api_key}- onChange={(e) =>- onChange({- ...value,- api_key: e.target.value,- } as OpenAIModelConfig)- }- disabled={disabled}- />- </div>- )}-- {value.model_type === "AzureOpenAIChatCompletionClient" && (- <Space direction="vertical" size="middle" style={{ width: "100%" }}>- <div>- <label className="block text-sm font-medium mb-2">- Azure Deployment- </label>- <Input- value={(value as AzureOpenAIModelConfig).azure_deployment}- onChange={(e) =>- onChange({- ...value,- azure_deployment: e.target.value,- } as AzureOpenAIModelConfig)- }- disabled={disabled}- />- </div>-- <div>- <label className="block text-sm font-medium mb-2">- API Version- </label>- <Input- value={(value as AzureOpenAIModelConfig).api_version}- onChange={(e) =>- onChange({- ...value,- api_version: e.target.value,- } as AzureOpenAIModelConfig)- }- disabled={disabled}- />- </div>-- <div>- <label className="block text-sm font-medium mb-2">- Azure Endpoint- </label>- <Input- value={(value as AzureOpenAIModelConfig).azure_endpoint}- onChange={(e) =>- onChange({- ...value,- azure_endpoint: e.target.value,- } as AzureOpenAIModelConfig)- }- disabled={disabled}- />- </div>- </Space>- )}- </Space>- );-};--const AgentEditor: React.FC<EditorProps<AgentConfig>> = ({- value,- onChange,- disabled,-}) => {- return (- <Space direction="vertical" size="large" style={{ width: "100%" }}>- <div>- <label className="block text-sm font-medium mb-2">Agent Type</label>- <Select- value={value.agent_type}- onChange={(type: AgentTypes) =>- onChange({ ...value, agent_type: type })- }- disabled={disabled}- style={{ width: "100%" }}- options={[- { value: "AssistantAgent", label: "Assistant Agent" },- { value: "CodingAssistantAgent", label: "Coding Assistant" },- { value: "UserProxyAgent", label: "User Proxy" },- { value: "MultimodalWebSurfer", label: "Web Surfer" },- { value: "FileSurfer", label: "File Surfer" },- { value: "MagenticOneCoderAgent", label: "Magnetic One Coder" },- ]}- />- </div>-- <div>- <label className="block text-sm font-medium mb-2">Name</label>- <Input- value={value.name}- onChange={(e) => onChange({ ...value, name: e.target.value })}- disabled={disabled}- />- </div>-- <div>- <label className="block text-sm font-medium mb-2">System Message</label>- <TextArea- value={value.system_message}- onChange={(e) =>- onChange({ ...value, system_message: e.target.value })- }- disabled={disabled}- rows={4}- />- </div>-- <div>- <label className="block text-sm font-medium mb-2">Description</label>- <TextArea- value={value.description}- onChange={(e) => onChange({ ...value, description: e.target.value })}- disabled={disabled}- rows={2}- />- </div>- </Space>- );-};--const ToolEditor: React.FC<EditorProps<ToolConfig>> = ({- value,- onChange,- disabled,-}) => {- return (- <Space direction="vertical" size="large" style={{ width: "100%" }}>- <div>- <label className="block text-sm font-medium mb-2">Tool Type</label>- <Select- value={value.tool_type}- onChange={(type: ToolTypes) =>- onChange({ ...value, tool_type: type })- }- disabled={disabled}- style={{ width: "100%" }}- options={[{ value: "PythonFunction", label: "Python Function" }]}- />- </div>-- <div>- <label className="block text-sm font-medium mb-2">Name</label>- <Input- value={value.name}- onChange={(e) => onChange({ ...value, name: e.target.value })}- disabled={disabled}- />- </div>-- <div>- <label className="block text-sm font-medium mb-2">Description</label>- <TextArea- value={value.description}- onChange={(e) => onChange({ ...value, description: e.target.value })}- disabled={disabled}- rows={2}- />- </div>-- <div>- <label className="block text-sm font-medium mb-2">Content</label>- <TextArea- value={value.content}- onChange={(e) => onChange({ ...value, content: e.target.value })}- disabled={disabled}- rows={8}- />- </div>- </Space>- );-};--const TerminationEditor: React.FC<EditorProps<TerminationConfig>> = ({- value,- onChange,- disabled,-}) => {- const handleTypeChange = (terminationType: TerminationTypes) => {- if (terminationType === "MaxMessageTermination") {- onChange({- component_type: "termination",- termination_type: terminationType,- max_messages: 100,- } as MaxMessageTerminationConfig);- } else if (terminationType === "TextMentionTermination") {- onChange({- component_type: "termination",- termination_type: terminationType,- text: "",- } as TextMentionTerminationConfig);- } else if (terminationType === "CombinationTermination") {- onChange({- component_type: "termination",- termination_type: terminationType,- operator: "or",- conditions: [],- } as CombinationTerminationConfig);- }- };-- const handleOperatorChange = (operator: "and" | "or") => {- if (value.termination_type === "CombinationTermination") {- onChange({- ...value,- operator,- } as CombinationTerminationConfig);- }- };-- const handleAddCondition = () => {- if (value.termination_type === "CombinationTermination") {- onChange({- ...value,- conditions: [- ...value.conditions,- {- component_type: "termination",- termination_type: "MaxMessageTermination",- max_messages: 100,- },- ],- } as CombinationTerminationConfig);- }- };-- const handleUpdateCondition = (- index: number,- newCondition: TerminationConfig- ) => {- if (value.termination_type === "CombinationTermination") {- const newConditions = [...value.conditions];- newConditions[index] = newCondition;- onChange({- ...value,- conditions: newConditions,- } as CombinationTerminationConfig);- }- };-- const handleRemoveCondition = (index: number) => {- if (value.termination_type === "CombinationTermination") {- onChange({- ...value,- conditions: value.conditions.filter((_, i) => i !== index),- } as CombinationTerminationConfig);- }- };-- return (- <Space direction="vertical" size="large" style={{ width: "100%" }}>- <div>- <label className="block text-sm font-medium mb-2">- Termination Type- </label>- <Select- value={value.termination_type}- onChange={handleTypeChange}- disabled={disabled}- style={{ width: "100%" }}- options={[- { value: "MaxMessageTermination", label: "Max Messages" },- { value: "TextMentionTermination", label: "Text Mention" },- { value: "CombinationTermination", label: "Combination" },- ]}- />- </div>-- {value.termination_type === "MaxMessageTermination" && (- <div>- <label className="block text-sm font-medium mb-2">Max Messages</label>- <Input- type="number"- value={(value as MaxMessageTerminationConfig).max_messages}- onChange={(e) =>- onChange({- ...value,- max_messages: parseInt(e.target.value),- } as MaxMessageTerminationConfig)- }- disabled={disabled}- />- </div>- )}-- {value.termination_type === "TextMentionTermination" && (- <div>- <label className="block text-sm font-medium mb-2">- Text to Match- </label>- <Input- value={(value as TextMentionTerminationConfig).text}- onChange={(e) =>- onChange({- ...value,- text: e.target.value,- } as TextMentionTerminationConfig)- }- disabled={disabled}- />- </div>- )}-- {value.termination_type === "CombinationTermination" && (- <Space direction="vertical" size="middle" style={{ width: "100%" }}>- <div>- <label className="block text-sm font-medium mb-2">Operator</label>- <Select- value={(value as CombinationTerminationConfig).operator}- onChange={handleOperatorChange}- disabled={disabled}- style={{ width: "100%" }}- options={[- { value: "and", label: "AND" },- { value: "or", label: "OR" },- ]}- />- </div>-- <div>- <label className="block text-sm font-medium mb-2">Conditions</label>- <Space direction="vertical" size="middle" style={{ width: "100%" }}>- {(value as CombinationTerminationConfig).conditions.map(- (condition, index) => (- <div key={index} className="border p-4 rounded-md">- <Space- direction="vertical"- size="middle"- style={{ width: "100%" }}- >- <TerminationEditor- value={condition}- onChange={(newCondition) =>- handleUpdateCondition(index, newCondition)- }- disabled={disabled}- />- <Button- danger- onClick={() => handleRemoveCondition(index)}- disabled={disabled}- >- Remove Condition- </Button>- </Space>- </div>- )- )}- <Button- type="dashed"- onClick={handleAddCondition}- disabled={disabled}- style={{ width: "100%" }}- >- Add Condition- </Button>- </Space>- </div>- </Space>- )}- </Space>- );-};--// Component type to editor mapping-const EditorComponents: Record<ComponentTypes, React.FC<EditorProps<any>>> = {- team: TeamEditor,- model: ModelEditor,- agent: AgentEditor,- tool: ToolEditor,- termination: TerminationEditor,-};--export const NodeEditor: React.FC<NodeEditorProps> = ({ node, onUpdate }) => {- const [isOpen, setIsOpen] = useState(false);- const [config, setConfig] = useState<ComponentConfigTypes | null>(null);- const [isSaving, setIsSaving] = useState(false);- const setSelectedNode = useTeamBuilderStore((state) => state.setSelectedNode);- const [messageApi, contextHolder] = message.useMessage();-- useEffect(() => {- if (node) {- setIsOpen(true);- setConfig(node.data.config as ComponentConfigTypes);- } else {- setIsOpen(false);- }- }, [node]);-- const handleClose = () => {- setSelectedNode(null);- };-- const handleSave = async () => {- try {- setIsSaving(true);- if (!config) throw new Error("No configuration to save");-- // Validate config based on its type- validateConfig(config);-- onUpdate({ config });- messageApi.success("Changes saved successfully");- setSelectedNode(null);- } catch (error) {- console.error("Save failed:", error);- messageApi.error(error instanceof Error ? error.message : "Save failed");- } finally {- setIsSaving(false);- }- };-- if (!node || !config) return null;-- const EditorComponent = EditorComponents[node.data.type];- if (!EditorComponent) return null;-- return (- <Drawer- title={`Edit ${node.data.label}`}- placement="right"- width={500}- open={isOpen}- onClose={handleClose}- extra={- <Space>- <Button onClick={handleClose}>Cancel</Button>- <Button type="primary" onClick={handleSave} loading={isSaving}>- Update- </Button>- </Space>- }- >- {contextHolder}- <EditorComponent- value={config}- onChange={setConfig}- disabled={isSaving}- />- </Drawer>- );-};--// Type-safe validation functions-function validateConfig(config: ComponentConfigTypes): void {- switch (config.component_type) {- case "team": {- const teamConfig = config as TeamConfig;- if ("selector_prompt" in teamConfig) {- // Type guard for SelectorGroupChatConfig- if (!teamConfig.selector_prompt) {- throw new Error("Selector prompt is required");- }- if (!teamConfig.model_client) {- throw new Error("Model configuration is required for selector team");- }- }- break;- }-- case "model":- const modelConfig = config as ModelConfig;- if ("AzureOpenAIChatCompletionClient" in modelConfig) {- const azureConfig = config as AzureOpenAIModelConfig;- if (- !azureConfig.azure_deployment ||- !azureConfig.api_version ||- !azureConfig.azure_endpoint- ) {- throw new Error("Azure OpenAI configuration is incomplete");- }- }- break;- // Add other type-specific validations as needed- }-}--export default NodeEditor;diff --git a/python/packages/autogen-studio/frontend/src/components/views/team/builder/node-editor/detailgroup.tsx b/python/packages/autogen-studio/frontend/src/components/views/team/builder/node-editor/detailgroup.tsxnew file mode 100644index 000000000..0f1da6561--- /dev/null+++ b/python/packages/autogen-studio/frontend/src/components/views/team/builder/node-editor/detailgroup.tsx@@ -0,0 +1,24 @@+import React from "react";++interface DetailGroupProps {+ title: string;+ children: React.ReactNode;+}++const DetailGroup: React.FC<DetailGroupProps> = ({ title, children }) => {+ return (+ <div className="relative mt-2 mb-4">+ {/* Border container with padding */}+ <div className="border border-secondary rounded-lg p-2 px-3 pt-6">+ {/* Floating title */}+ <div className="absolute -top-3 left-3 px-2 bg-primary">+ <span className="text-xs text-primary">{title}</span>+ </div>+ {/* Content */}+ <div>{children}</div>+ </div>+ </div>+ );+};++export default DetailGroup;diff --git a/python/packages/autogen-studio/frontend/src/components/views/team/builder/node-editor/fields.tsx b/python/packages/autogen-studio/frontend/src/components/views/team/builder/node-editor/fields.tsxnew file mode 100644index 000000000..9130b2e52--- /dev/null+++ b/python/packages/autogen-studio/frontend/src/components/views/team/builder/node-editor/fields.tsx@@ -0,0 +1,524 @@+import React from "react";+import { Input, Select, Switch, InputNumber, Form, Button } from "antd";+import { Edit } from "lucide-react";+import {+ isTeamComponent,+ isAgentComponent,+ isModelComponent,+ isToolComponent,+ isTerminationComponent,+ isSelectorTeam,+ isRoundRobinTeam,+ isAssistantAgent,+ isUserProxyAgent,+ isWebSurferAgent,+ isOpenAIModel,+ isAzureOpenAIModel,+ isFunctionTool,+ isOrTermination,+ isMaxMessageTermination,+ isTextMentionTermination,+} from "../../../../types/guards";+import { Component, ComponentConfig } from "../../../../types/datamodel";+import DetailGroup from "./detailgroup";++const { TextArea } = Input;+const { Option } = Select;++interface NodeEditorFieldsProps {+ component: Component<ComponentConfig>;+ onNavigate: (componentType: string, id: string, parentField: string) => void;+}++export const NodeEditorFields: React.FC<NodeEditorFieldsProps> = ({+ component,+ onNavigate,+}) => {+ const renderNestedComponentButton = (+ label: string,+ component: Component<ComponentConfig> | Component<ComponentConfig>[],+ parentField: string+ ) => {+ if (Array.isArray(component)) {+ return (+ <div className="space-y-2 mb-4">+ <div className="flex justify-between items-center">+ <span className="text-sm font-medium">{label}</span>+ </div>+ {component.map((item) => (+ <Button+ key={item.label}+ onClick={() =>+ onNavigate(item.component_type, item.label || "", parentField)+ }+ className="w-full flex justify-between items-center"+ >+ <span>{item.label}</span>+ <Edit className="w-4 h-4" />+ </Button>+ ))}+ </div>+ );+ }++ return component ? (+ <div className="mb-4">+ <Button+ onClick={() =>+ onNavigate(+ component.component_type,+ component.label || "",+ parentField+ )+ }+ className="w-full flex justify-between items-center"+ >+ <span>{label}</span>+ <Edit className="w-4 h-4" />+ </Button>+ </div>+ ) : null;+ };++ const renderTeamFields = () => {+ if (!component) return null;++ if (isSelectorTeam(component)) {+ return (+ <>+ <Form.Item+ label="Selector Prompt"+ name={["config", "selector_prompt"]}+ rules={[{ required: true }]}+ >+ <TextArea rows={4} />+ </Form.Item>+ <Form.Item label="Max Turns" name={["config", "max_turns"]}>+ <InputNumber min={1} />+ </Form.Item>+ <Form.Item+ label="Allow Repeated Speaker"+ name={["config", "allow_repeated_speaker"]}+ valuePropName="checked"+ >+ <Switch />+ </Form.Item>+ {component.config.model_client &&+ renderNestedComponentButton(+ "Model Client",+ component.config.model_client,+ "model_client"+ )}+ {component.config.termination_condition &&+ renderNestedComponentButton(+ "Termination Condition",+ component.config.termination_condition,+ "termination_condition"+ )}+ </>+ );+ }+ if (isRoundRobinTeam(component)) {+ return (+ <>+ <Form.Item label="Max Turns" name={["config", "max_turns"]}>+ <InputNumber min={1} />+ </Form.Item>+ {component.config.termination_condition &&+ renderNestedComponentButton(+ "Termination Condition",+ component.config.termination_condition,+ "termination_condition"+ )}+ </>+ );+ }+ return null;+ };++ const renderAgentFields = () => {+ if (!component) return null;++ if (isAssistantAgent(component)) {+ return (+ <>+ <Form.Item+ label="Name"+ name={["config", "name"]}+ rules={[{ required: true }]}+ >+ <Input />+ </Form.Item>+ <Form.Item+ label="Description"+ name={["config", "description"]}+ rules={[{ required: true }]}+ >+ <TextArea rows={4} />+ </Form.Item>+ <Form.Item label="System Message" name={["config", "system_message"]}>+ <TextArea rows={4} />+ </Form.Item>+ <Form.Item+ label="Reflect on Tool Use"+ name={["config", "reflect_on_tool_use"]}+ valuePropName="checked"+ >+ <Switch />+ </Form.Item>+ <Form.Item+ label="Tool Call Summary Format"+ name={["config", "tool_call_summary_format"]}+ >+ <Input />+ </Form.Item>+ {component.config.model_client &&+ renderNestedComponentButton(+ "Model Client",+ component.config.model_client,+ "model_client"+ )}+ {component.config.tools &&+ component.config.tools.length > 0 &&+ renderNestedComponentButton(+ "Tools",+ component.config.tools,+ "tools"+ )}+ </>+ );+ }+ if (isUserProxyAgent(component)) {+ return (+ <>+ <Form.Item+ label="Name"+ name={["config", "name"]}+ rules={[{ required: true }]}+ >+ <Input />+ </Form.Item>+ <Form.Item+ label="Description"+ name={["config", "description"]}+ rules={[{ required: true }]}+ >+ <TextArea rows={4} />+ </Form.Item>+ </>+ );+ }+ if (isWebSurferAgent(component)) {+ return (+ <>+ <Form.Item+ label="Name"+ name={["config", "name"]}+ rules={[{ required: true }]}+ >+ <Input />+ </Form.Item>+ <Form.Item+ label="Downloads Folder"+ name={["config", "downloads_folder"]}+ >+ <Input />+ </Form.Item>+ <Form.Item label="Description" name={["config", "description"]}>+ <TextArea rows={4} />+ </Form.Item>+ <Form.Item label="Start Page" name={["config", "start_page"]}>+ <Input />+ </Form.Item>+ <Form.Item+ label="Headless"+ name={["config", "headless"]}+ valuePropName="checked"+ >+ <Switch />+ </Form.Item>+ <Form.Item+ label="Animate Actions"+ name={["config", "animate_actions"]}+ valuePropName="checked"+ >+ <Switch />+ </Form.Item>+ <Form.Item+ label="Save Screenshots"+ name={["config", "to_save_screenshots"]}+ valuePropName="checked"+ >+ <Switch />+ </Form.Item>+ <Form.Item+ label="Use OCR"+ name={["config", "use_ocr"]}+ valuePropName="checked"+ >+ <Switch />+ </Form.Item>+ <Form.Item+ label="Browser Channel"+ name={["config", "browser_channel"]}+ >+ <Input />+ </Form.Item>+ <Form.Item+ label="Browser Data Directory"+ name={["config", "browser_data_dir"]}+ >+ <Input />+ </Form.Item>+ <Form.Item+ label="Resize Viewport"+ name={["config", "to_resize_viewport"]}+ valuePropName="checked"+ >+ <Switch />+ </Form.Item>+ {component.config.model_client &&+ renderNestedComponentButton(+ "Model Client",+ component.config.model_client,+ "model_client"+ )}+ </>+ );+ }+ return null;+ };++ const renderModelFields = () => {+ if (!component) return null;++ const createArgumentsFields = (+ <>+ <Form.Item label="Temperature" name={["config", "temperature"]}>+ <InputNumber min={0} max={2} step={0.1} />+ </Form.Item>+ <Form.Item label="Max Tokens" name={["config", "max_tokens"]}>+ <InputNumber min={1} />+ </Form.Item>+ <Form.Item label="Top P" name={["config", "top_p"]}>+ <InputNumber min={0} max={1} step={0.1} />+ </Form.Item>+ <Form.Item+ label="Frequency Penalty"+ name={["config", "frequency_penalty"]}+ >+ <InputNumber min={-2} max={2} step={0.1} />+ </Form.Item>+ <Form.Item+ label="Presence Penalty"+ name={["config", "presence_penalty"]}+ >+ <InputNumber min={-2} max={2} step={0.1} />+ </Form.Item>+ <Form.Item label="Stop Sequences" name={["config", "stop"]}>+ <Select mode="tags" />+ </Form.Item>+ </>+ );++ if (isOpenAIModel(component)) {+ return (+ <>+ <Form.Item+ label="Model"+ name={["config", "model"]}+ rules={[{ required: true }]}+ >+ <Input />+ </Form.Item>+ <Form.Item label="API Key" name={["config", "api_key"]}>+ <Input.Password />+ </Form.Item>+ <Form.Item label="Organization" name={["config", "organization"]}>+ <Input />+ </Form.Item>+ <Form.Item label="Base URL" name={["config", "base_url"]}>+ <Input />+ </Form.Item>+ <Form.Item label="Timeout" name={["config", "timeout"]}>+ <InputNumber min={1} />+ </Form.Item>+ <Form.Item label="Max Retries" name={["config", "max_retries"]}>+ <InputNumber min={0} />+ </Form.Item>+ {createArgumentsFields}+ </>+ );+ }+ if (isAzureOpenAIModel(component)) {+ return (+ <>+ <Form.Item+ label="Model"+ name={["config", "model"]}+ rules={[{ required: true }]}+ >+ <Input />+ </Form.Item>+ <Form.Item+ label="Azure Endpoint"+ name={["config", "azure_endpoint"]}+ rules={[{ required: true }]}+ >+ <Input />+ </Form.Item>+ <Form.Item+ label="Azure Deployment"+ name={["config", "azure_deployment"]}+ >+ <Input />+ </Form.Item>+ <Form.Item+ label="API Version"+ name={["config", "api_version"]}+ rules={[{ required: true }]}+ >+ <Input />+ </Form.Item>+ <Form.Item label="Azure AD Token" name={["config", "azure_ad_token"]}>+ <Input.Password />+ </Form.Item>+ {createArgumentsFields}+ </>+ );+ }+ return null;+ };++ const renderToolFields = () => {+ if (!component) return null;++ if (isFunctionTool(component)) {+ return (+ <>+ <Form.Item+ label="Name"+ name={["config", "name"]}+ rules={[{ required: true }]}+ >+ <Input />+ </Form.Item>+ <Form.Item+ label="Description"+ name={["config", "description"]}+ rules={[{ required: true }]}+ >+ <TextArea rows={4} />+ </Form.Item>+ <Form.Item+ label="Source Code"+ name={["config", "source_code"]}+ rules={[{ required: true }]}+ >+ <TextArea rows={8} />+ </Form.Item>+ <Form.Item+ label="Has Cancellation Support"+ name={["config", "has_cancellation_support"]}+ valuePropName="checked"+ >+ <Switch />+ </Form.Item>+ </>+ );+ }+ return null;+ };++ const renderTerminationFields = () => {+ if (!component) return null;++ if (isOrTermination(component)) {+ return (+ <>+ <Form.Item+ label="Number of Conditions"+ name={["config", "conditions"]}+ >+ <InputNumber disabled />+ </Form.Item>+ {component.config.conditions &&+ component.config.conditions.length > 0 &&+ renderNestedComponentButton(+ "Conditions",+ component.config.conditions,+ "conditions"+ )}+ </>+ );+ }+ if (isMaxMessageTermination(component)) {+ return (+ <Form.Item+ label="Max Messages"+ name={["config", "max_messages"]}+ rules={[{ required: true }]}+ >+ <InputNumber min={1} />+ </Form.Item>+ );+ }+ if (isTextMentionTermination(component)) {+ return (+ <Form.Item+ label="Text"+ name={["config", "text"]}+ rules={[{ required: true }]}+ >+ <Input />+ </Form.Item>+ );+ }+ return null;+ };++ // Common fields for all components+ const commonFields = (+ <DetailGroup title="Component Details">+ <Form.Item label="Label" name="label">+ <Input />+ </Form.Item>+ <Form.Item label="Description" name="description">+ <TextArea rows={4} />+ </Form.Item>+ </DetailGroup>+ );+ // Component-specific fields+ let specificFields = null;+ if (isTeamComponent(component)) {+ specificFields = (+ <DetailGroup title="Configuration">{renderTeamFields()}</DetailGroup>+ );+ } else if (isAgentComponent(component)) {+ specificFields = (+ <DetailGroup title="Configuration">{renderAgentFields()}</DetailGroup>+ );+ } else if (isModelComponent(component)) {+ specificFields = (+ <DetailGroup title="Configuration">{renderModelFields()}</DetailGroup>+ );+ } else if (isToolComponent(component)) {+ specificFields = (+ <DetailGroup title="Configuration">{renderToolFields()}</DetailGroup>+ );+ } else if (isTerminationComponent(component)) {+ specificFields = (+ <DetailGroup title="Configuration">+ {renderTerminationFields()}+ </DetailGroup>+ );+ }+ return (+ <>+ {commonFields}+ {specificFields}+ </>+ );+};++export default NodeEditorFields;diff --git a/python/packages/autogen-studio/frontend/src/components/views/team/builder/node-editor/node-editor.tsx b/python/packages/autogen-studio/frontend/src/components/views/team/builder/node-editor/node-editor.tsxnew file mode 100644index 000000000..d9b6f6f17--- /dev/null+++ b/python/packages/autogen-studio/frontend/src/components/views/team/builder/node-editor/node-editor.tsx@@ -0,0 +1,291 @@+import React from "react";+import { Form, Button, Drawer, Breadcrumb } from "antd";+import { ChevronLeft } from "lucide-react";+import { Component, ComponentConfig } from "../../../../types/datamodel";+import { NodeEditorProps } from "../types";+import NodeEditorFields from "./fields";+import { isComponent } from "../../../../types/guards";++interface EditPath {+ componentType: string;+ id: string;+ parentField: string;+}++export const NodeEditor: React.FC<+ NodeEditorProps & { onClose: () => void }+> = ({ node, onUpdate, onClose }) => {+ const [form] = Form.useForm();+ const [editPath, setEditPath] = React.useState<EditPath[]>([]);++ // Keep a working copy of the entire component structure+ const [workingCopy, setWorkingCopy] =+ React.useState<Component<ComponentConfig> | null>(+ node ? { ...node.data.component } : null+ );++ // Reset working copy when node changes+ React.useEffect(() => {+ if (node) {+ setWorkingCopy({ ...node.data.component });+ setEditPath([]);+ } else {+ setWorkingCopy(null);+ }+ }, [node]);++ // Initialize form values when edit path changes+ React.useEffect(() => {+ if (workingCopy) {+ const currentComponent = getCurrentComponent(workingCopy);+ if (currentComponent) {+ // Create form values object matching the field structure in NodeEditorFields+ const formValues = {+ label: currentComponent.label,+ description: currentComponent.description,+ // For each config field, create an array path ["config", "fieldname"]+ ...Object.entries(currentComponent.config).reduce(+ (acc, [key, value]) => {+ // Skip nested component fields as they're handled by buttons+ if (+ typeof value === "object" &&+ (Array.isArray(value) || value?.component_type)+ ) {+ return acc;+ }+ return {+ ...acc,+ config: {+ ...acc.config,+ [key]: value,+ },+ };+ },+ { config: {} }+ ),+ };++ form.setFieldsValue(formValues);+ }+ }+ }, [workingCopy, form, editPath]);++ if (!node || !workingCopy) return null;++ const getCurrentComponent = (root: Component<ComponentConfig>) => {+ let current: Component<ComponentConfig> = root;++ for (const path of editPath) {+ const field = current.config[+ path.parentField as keyof typeof current.config+ ] as+ | Component<ComponentConfig>[]+ | Component<ComponentConfig>+ | undefined;++ if (Array.isArray(field)) {+ // For arrays, try to find the component by its label first, then by name+ const found = field.find(+ (item) =>+ item.label === path.id ||+ (item.config &&+ "name" in item.config &&+ item.config.name === path.id)+ );+ if (!found) return null;+ current = found;+ } else if (field) {+ // For single components, just use the field directly+ current = field;+ } else {+ return null;+ }+ }++ return current;+ };++ const updateComponentAtPath = <T extends ComponentConfig>(+ root: Component<T>,+ path: EditPath[],+ updates: Partial<Component<T>>+ ): Component<T> => {+ if (path.length === 0) {+ return {+ ...root,+ ...updates,+ config: {+ ...root.config,+ ...(updates.config || {}),+ },+ };+ }++ const [currentPath, ...remainingPath] = path;+ const result = { ...root };+ const field = result.config[currentPath.parentField as keyof T];+ const updatedConfig = { ...result.config } as T;++ if (Array.isArray(field)) {+ updatedConfig[currentPath.parentField as keyof T] = field.map((item) => {+ if (!isComponent(item)) return item;++ if (+ item.label === currentPath.id ||+ ("name" in item.config && item.config.name === currentPath.id)+ ) {+ return updateComponentAtPath(item, remainingPath, updates);+ }+ return item;+ }) as T[keyof T];+ } else if (field && isComponent(field)) {+ updatedConfig[currentPath.parentField as keyof T] = updateComponentAtPath(+ field,+ remainingPath,+ updates+ ) as T[keyof T];+ }++ return {+ ...result,+ config: updatedConfig,+ };+ };++ const navigateToComponent = (+ componentType: string,+ id: string,+ parentField: string+ ) => {+ console.log("Navigating to:", { componentType, id, parentField });++ // Update working copy with current form values before navigating+ const values = form.getFieldsValue();+ const updatedCopy = updateComponentAtPath(workingCopy, editPath, {+ label: values.label,+ description: values.description,+ config: {+ ...getCurrentComponent(workingCopy)?.config,+ ...values,+ },+ });+ setWorkingCopy(updatedCopy);++ // Navigate to new path+ const newPath = [...editPath, { componentType, id, parentField }];+ console.log("New edit path:", newPath);+ setEditPath(newPath);++ // Log the component we're going to+ const nextComponent = getCurrentComponent(updatedCopy);+ console.log("Next component:", nextComponent);+ };++ const navigateBack = () => {+ // Update working copy with current form values before navigating back+ const values = form.getFieldsValue();+ const updatedCopy = updateComponentAtPath(workingCopy, editPath, {+ label: values.label,+ description: values.description,+ config: values,+ });+ setWorkingCopy(updatedCopy);++ // Navigate back+ setEditPath(editPath.slice(0, -1));+ };++ const handleFormSubmit = async () => {+ try {+ const values = await form.validateFields();+ console.log("Form values on submit:", values);++ // Get the current component to preserve any nested components+ const currentComponent = getCurrentComponent(workingCopy);++ // Construct the updated component+ const updatedComponent = {+ ...currentComponent,+ label: values.label,+ description: values.description,+ config: {+ ...currentComponent?.config, // Preserve nested components+ ...values.config, // Update with new form values+ },+ };++ console.log("Updating component with:", updatedComponent);++ // Update working copy+ const finalCopy = updateComponentAtPath(+ workingCopy,+ editPath,+ updatedComponent+ );++ // Submit the entire working copy to parent+ onUpdate({+ ...node.data,+ component: finalCopy,+ });+ } catch (error) {+ console.error("Validation failed:", error);+ }+ };++ const getBreadcrumbItems = () => {+ return [+ { title: workingCopy.label || "Root" },+ ...editPath.map((path) => ({+ title: path.id,+ })),+ ];+ };++ const currentComponent = getCurrentComponent(workingCopy);++ return (+ <Drawer+ title={+ <div className="flex items-center gap-4">+ {editPath.length > 0 && (+ <Button+ onClick={navigateBack}+ icon={<ChevronLeft className="w-4 h-4" />}+ type="text"+ />+ )}+ <div className="flex-1">+ <Breadcrumb items={getBreadcrumbItems()} />+ </div>+ </div>+ }+ placement="right"+ width={400}+ onClose={onClose}+ open={true}+ className="node-editor-drawer"+ >+ <Form+ form={form}+ layout="vertical"+ className="h-full overflow-y-auto pb-16"+ >+ {currentComponent && (+ <NodeEditorFields+ component={currentComponent}+ onNavigate={navigateToComponent}+ />+ )}+ <div className="flex justify-end gap-2 mt-4 absolute bottom-0 right-0 left-0 p-4 bg-white border-t">+ <Button onClick={onClose}>Cancel</Button>+ <Button type="primary" onClick={handleFormSubmit}>+ Save Changes+ </Button>+ </div>+ </Form>+ </Drawer>+ );+};++export default NodeEditor;diff --git a/python/packages/autogen-studio/frontend/src/components/views/team/builder/nodes.tsx b/python/packages/autogen-studio/frontend/src/components/views/team/builder/nodes.tsxindex 7701e11d2..d70d11efd 100644--- a/python/packages/autogen-studio/frontend/src/components/views/team/builder/nodes.tsx+++ b/python/packages/autogen-studio/frontend/src/components/views/team/builder/nodes.tsx@@ -1,4 +1,4 @@-import React from "react";+import React, { memo } from "react";import {Handle,Position,@@ -26,13 +26,29 @@ import {ToolConfig,TerminationConfig,ComponentTypes,+ Component,+ ComponentConfig,} from "../../../types/datamodel";import { useDroppable } from "@dnd-kit/core";import { TruncatableText } from "../../atoms";import { useTeamBuilderStore } from "./store";+import {+ isAssistantAgent,+ isAzureOpenAIModel,+ isFunctionTool,+ isMaxMessageTermination,+ isOpenAIModel,+ isOrTermination,+ isSelectorTeam,+ isTextMentionTermination,+ isWebSurferAgent,+} from "../../../types/guards";// Icon mapping for different node types-const iconMap: Record<NodeData["type"], LucideIcon> = {+const iconMap: Record<+ Component<ComponentConfig>["component_type"],+ LucideIcon+> = {team: Users,agent: Bot,tool: Wrench,@@ -47,34 +63,32 @@ interface DroppableZoneProps {id: string; // Add this to make each zone uniquely identifiable}-const DroppableZone: React.FC<DroppableZoneProps> = ({- accepts,- children,- className,- id,-}) => {- const { isOver, setNodeRef, active } = useDroppable({- id,- data: { accepts },- });-- // Fix the data path to handle nested current objects- const isValidDrop =- isOver &&- active?.data?.current?.current?.type &&- accepts.includes(active.data.current.current.type);-- return (- <div- ref={setNodeRef}- className={`droppable-zone p-2 ${isValidDrop ? "can-drop" : ""} ${- className || ""- }`}- >- {children}- </div>- );-};+const DroppableZone = memo<DroppableZoneProps>(+ ({ accepts, children, className, id }) => {+ const { isOver, setNodeRef, active } = useDroppable({+ id,+ data: { accepts },+ });++ // Fix the data path to handle nested current objects+ const isValidDrop =+ isOver &&+ active?.data?.current?.current?.type &&+ accepts.includes(active.data.current.current.type);++ return (+ <div+ ref={setNodeRef}+ className={`droppable-zone p-2 ${isValidDrop ? "can-drop" : ""} ${+ className || ""+ }`}+ >+ {children}+ </div>+ );+ }+);+DroppableZone.displayName = "DroppableZone";// Base node layout componentinterface BaseNodeProps extends NodeProps<CustomNode> {@@ -87,85 +101,86 @@ interface BaseNodeProps extends NodeProps<CustomNode> {onEditClick?: (id: string) => void;}-const BaseNode: React.FC<BaseNodeProps> = ({- id,- data,- selected,- dragHandle,- icon: Icon,- children,- headerContent,- descriptionContent,- className,- onEditClick,-}) => {- const removeNode = useTeamBuilderStore((state) => state.removeNode);- const setSelectedNode = useTeamBuilderStore((state) => state.setSelectedNode);- const showDelete = data.type !== "team";-- return (- <div- ref={dragHandle}- className={`+const BaseNode = memo<BaseNodeProps>(+ ({+ id,+ data,+ selected,+ dragHandle,+ icon: Icon,+ children,+ headerContent,+ descriptionContent,+ className,+ onEditClick,+ }) => {+ const removeNode = useTeamBuilderStore((state) => state.removeNode);+ const setSelectedNode = useTeamBuilderStore(+ (state) => state.setSelectedNode+ );+ const showDelete = data.type !== "team";++ return (+ <div+ ref={dragHandle}+ className={`bg-white text-primary relative rounded-lg shadow-lg w-72${selected ? "ring-2 ring-accent" : ""}${className || ""}transition-all duration-200`}- >- <div className="border-b p-3 bg-gray-50 rounded-t-lg">- <div className="flex items-center justify-between min-w-0">- <div className="flex items-center gap-2 min-w-0 flex-1">- <Icon className="flex-shrink-0 w-5 h-5 text-gray-600" />- <span className="font-medium text-gray-800 truncate">- {data.label}- </span>- </div>- <div className="flex items-center gap-2 flex-shrink-0">- <span className="text-xs px-2 py-1 bg-gray-200 rounded text-gray-700">- {data.type}- </span>- <button- onClick={(e) => {- e.stopPropagation();- setSelectedNode(id);- }}- className="p-1 hover:bg-secondary rounded"- >- <Edit className="w-4 h-4 text-accent" />- </button>- {showDelete && (- <>- <button- onClick={(e) => {- console.log("remove node", id);- e.stopPropagation();- if (id) removeNode(id);- }}- className="p-1 hover:bg-red-100 rounded"- >- <Trash2Icon className="w-4 h-4 text-red-500" />- </button>- </>- )}+ >+ <div className="border-b p-3 bg-gray-50 rounded-t-lg">+ <div className="flex items-center justify-between min-w-0">+ <div className="flex items-center gap-2 min-w-0 flex-1">+ <Icon className="flex-shrink-0 w-5 h-5 text-gray-600" />+ <span className="font-medium text-gray-800 truncate">+ {data.component.label}+ </span>+ </div>+ <div className="flex items-center gap-2 flex-shrink-0">+ <span className="text-xs px-2 py-1 bg-gray-200 rounded text-gray-700">+ {data.component.component_type}+ </span>+ <button+ onClick={(e) => {+ e.stopPropagation();+ setSelectedNode(id);+ }}+ className="p-1 hover:bg-secondary rounded"+ >+ <Edit className="w-4 h-4 text-accent" />+ </button>+ {showDelete && (+ <>+ <button+ onClick={(e) => {+ console.log("remove node", id);+ e.stopPropagation();+ if (id) removeNode(id);+ }}+ className="p-1 hover:bg-red-100 rounded"+ >+ <Trash2Icon className="w-4 h-4 text-red-500" />+ </button>+ </>+ )}+ </div></div>+ {headerContent}</div>- {headerContent}- </div>- {data.config.description && (<div className="px-3 py-2 border-b text-sm text-gray-600">- <TruncatableText- content={data.config.description}- textThreshold={150}- />+ {descriptionContent}</div>- )}- <div className="p-3 space-y-2">{children}</div>- </div>- );-};+ <div className="p-3 space-y-2">{children}</div>+ </div>+ );+ }+);++BaseNode.displayName = "BaseNode";// Reusable componentsconst NodeSection: React.FC<{@@ -193,11 +208,10 @@ const ConnectionBadge: React.FC<{);// Team Node-export const TeamNode: React.FC<NodeProps<CustomNode>> = (props) => {- const config = props.data.config as TeamConfig;- const hasModel =- config.team_type === "SelectorGroupChat" && !!config.model_client;- const participantCount = config.participants?.length || 0;+export const TeamNode = memo<NodeProps<CustomNode>>((props) => {+ const component = props.data.component as Component<TeamConfig>;+ const hasModel = isSelectorTeam(component) && !!component.config.model_client;+ const participantCount = component.config.participants?.length || 0;return (<BaseNode@@ -208,7 +222,7 @@ export const TeamNode: React.FC<NodeProps<CustomNode>> = (props) => {<ConnectionBadge connected={hasModel} label="Model" /><ConnectionBadgeconnected={participantCount > 0}- label={`${participantCount} Agent ${+ label={`${participantCount} Agent${participantCount > 1 ? "s" : ""}`}/>@@ -216,34 +230,40 @@ export const TeamNode: React.FC<NodeProps<CustomNode>> = (props) => {}descriptionContent={<div>- <div>Type: {config.team_type}</div>- {config.team_type === "SelectorGroupChat" &&- config.selector_prompt && (- <div className="mt-1 text-xs">- Selector:{" "}- <TruncatableText- content={config.selector_prompt}- textThreshold={150}- />- </div>- )}+ <div>+ <TruncatableText+ content={component.description || component.label || ""}+ textThreshold={150}+ />+ </div>+ {isSelectorTeam(component) && component.config.selector_prompt && (+ <div className="mt-1 text-xs">+ Selector:{" "}+ <TruncatableText+ content={component.config.selector_prompt}+ textThreshold={150}+ />+ </div>+ )}</div>}>- {config.team_type === "SelectorGroupChat" && (+ {isSelectorTeam(component) && (<NodeSection title="Model">- <Handle+ {/* <Handletype="target"position={Position.Left}id={`${props.id}-model-input-handle`}className="my-left-handle"- />+ /> */}<div className="relative">{hasModel && (- <div className="text-sm">{config.model_client.model}</div>+ <div className="text-sm">+ {component.config.model_client.config.model}+ </div>)}- <DroppableZone id={`${props.id}-model-zone`} accepts={["model"]}>+ <DroppableZone id={`${props.id}@@@model-zone`} accepts={["model"]}><div className="text-secondary text-xs my-1 text-center">Drop model here</div>@@ -260,25 +280,23 @@ export const TeamNode: React.FC<NodeProps<CustomNode>> = (props) => {</div>}>- {true && (- <Handle- type="source"- position={Position.Right}- id={`${props.id}-agent-output-handle`}- className="my-right-handle"- />- )}+ <Handle+ type="source"+ position={Position.Right}+ id={`${props.id}-agent-output-handle`}+ className="my-right-handle"+ /><div className="space-y-1">- {config.participants?.map((participant, index) => (+ {component.config.participants?.map((participant, index) => (<divkey={index}className="relative text-sm py-1 px-2 bg-white rounded flex items-center gap-2"><Brain className="w-4 h-4 text-gray-500" />- <span>{participant.name}</span>+ <span>{participant.config.name}</span></div>))}- <DroppableZone id={`${props.id}-agent-zone`} accepts={["agent"]}>+ <DroppableZone id={`${props.id}@@@agent-zone`} accepts={["agent"]}><div className="text-secondary text-xs my-1 text-center">Drop agents here</div>@@ -287,19 +305,22 @@ export const TeamNode: React.FC<NodeProps<CustomNode>> = (props) => {</NodeSection><NodeSection title="Terminations">- {config.termination_condition && (+ {/* {<Handletype="target"position={Position.Left}id={`${props.id}-termination-input-handle`}className="my-left-handle"/>- )}+ } */}<div className="space-y-1">- {config.termination_condition && (+ {component.config.termination_condition && (<div className="text-sm py-1 px-2 bg-white rounded flex items-center gap-2"><Timer className="w-4 h-4 text-gray-500" />- <span>{config.termination_condition.termination_type}</span>+ <span>+ {component.config.termination_condition.label ||+ component.config.termination_condition.component_type}+ </span></div>)}<DroppableZone@@ -314,12 +335,17 @@ export const TeamNode: React.FC<NodeProps<CustomNode>> = (props) => {</NodeSection></BaseNode>);-};+});-export const AgentNode: React.FC<NodeProps<CustomNode>> = (props) => {- const config = props.data.config as AgentConfig;- const hasModel = !!config.model_client;- const toolCount = config.tools?.length || 0;+TeamNode.displayName = "TeamNode";++export const AgentNode = memo<NodeProps<CustomNode>>((props) => {+ const component = props.data.component as Component<AgentConfig>;+ const hasModel =+ isAssistantAgent(component) && !!component.config.model_client;+ const toolCount = isAssistantAgent(component)+ ? component.config.tools?.length || 0+ : 0;return (<BaseNode@@ -327,24 +353,24 @@ export const AgentNode: React.FC<NodeProps<CustomNode>> = (props) => {icon={iconMap.agent}headerContent={<div className="flex gap-2 mt-2">- <ConnectionBadge connected={hasModel} label="Model" />- <ConnectionBadge- connected={toolCount > 0}- label={`${toolCount} Tools`}- />+ {isAssistantAgent(component) && (+ <>+ <ConnectionBadge connected={hasModel} label="Model" />+ <ConnectionBadge+ connected={toolCount > 0}+ label={`${toolCount} Tools`}+ />+ </>+ )}</div>}descriptionContent={<div>- <div>Type: {config.agent_type}</div>- {config.system_message && (- <div className="mt-1 text-xs">- <TruncatableText- content={config.system_message}- textThreshold={150}- />- </div>- )}+ <div className="break-words truncate mb-1">+ {" "}+ {component.config.name}+ </div>+ <div className="break-words"> {component.description}</div></div>}>@@ -352,185 +378,124 @@ export const AgentNode: React.FC<NodeProps<CustomNode>> = (props) => {type="target"position={Position.Left}id={`${props.id}-agent-input-handle`}- className="my-left-handle"+ className="my-left-handle z-100"/>- <NodeSection title="Model">- <Handle- type="target"- position={Position.Left}- id={`${props.id}-model-input-handle`}- className="my-left-handle"- />-- <div className="relative">- {config.model_client && (- <>- {" "}- <div className="text-sm">{config.model_client.model}</div>- </>- )}- <DroppableZone id={`${props.id}-model-zone`} accepts={["model"]}>- <div className="text-secondary text-xs my-1 text-center">- Drop model here- </div>- </DroppableZone>- </div>- </NodeSection>-- <NodeSection title="Tools">- {- <Handle- type="target"- position={Position.Left}- id={`${props.id}-tool-input-handle`}- className="my-left-handle"- />- }- <div className="space-y-1">- {config.tools && toolCount > 0 && (- <div className="space-y-1">- {config.tools.map((tool, index) => (- <div- key={index}- className="relative text-sm py-1 px-2 bg-white rounded flex items-center gap-2"- >- <Wrench className="w-4 h-4 text-gray-500" />- <span>{tool.name}</span>+ {(isAssistantAgent(component) || isWebSurferAgent(component)) && (+ <>+ <NodeSection title="Model">+ {/* <Handle+ type="target"+ position={Position.Left}+ id={`${props.id}-model-input-handle`}+ className="my-left-handle"+ /> */}++ <div className="relative">+ {component.config.model_client && (+ <div className="text-sm">+ {component.config.model_client.config.model}</div>- ))}- </div>- )}- <DroppableZone id={`${props.id}-tool-zone`} accepts={["tool"]}>- <div className="text-secondary text-xs my-1 text-center">- Drop tools here+ )}+ <DroppableZone+ id={`${props.id}@@@model-zone`}+ accepts={["model"]}+ >+ <div className="text-secondary text-xs my-1 text-center">+ Drop model here+ </div>+ </DroppableZone></div>- </DroppableZone>- </div>- </NodeSection>- </BaseNode>- );-};--// Model Node-export const ModelNode: React.FC<NodeProps<CustomNode>> = (props) => {- const config = props.data.config as ModelConfig;-- return (- <BaseNode- {...props}- icon={iconMap.model}- descriptionContent={- <div>- <div>Type: {config.model_type}</div>- {config.base_url && (- <div className="mt-1 text-xs">URL: {config.base_url}</div>+ </NodeSection>++ {isAssistantAgent(component) && (+ <NodeSection title="Tools">+ {/* <Handle+ type="target"+ position={Position.Left}+ id={`${props.id}-tool-input-handle`}+ className="my-left-handle"+ /> */}+ <div className="space-y-1">+ {component.config.tools && toolCount > 0 && (+ <div className="space-y-1">+ {component.config.tools.map((tool, index) => (+ <div+ key={index}+ className="relative text-sm py-1 px-2 bg-white rounded flex items-center gap-2"+ >+ <Wrench className="w-4 h-4 text-gray-500" />+ <span>{tool.config.name}</span>+ </div>+ ))}+ </div>+ )}+ <DroppableZone+ id={`${props.id}@@@tool-zone`}+ accepts={["tool"]}+ >+ <div className="text-secondary text-xs my-1 text-center">+ Drop tools here+ </div>+ </DroppableZone>+ </div>+ </NodeSection>)}- </div>- }- >- <Handle- type="source" // This model's handle should be source since it connects TO team/agent- position={Position.Right}- id={`${props.id}-model-output-handle`}- className="my-right-handle"- />- <NodeSection title="Configuration">- <div className="text-sm">Model: {config.model}</div>- </NodeSection>- </BaseNode>- );-};--// Tool Node-export const ToolNode: React.FC<NodeProps<CustomNode>> = (props) => {- const config = props.data.config as ToolConfig;-- return (- <BaseNode- {...props}- icon={iconMap.tool}- descriptionContent={<div>Tool Type: {config.tool_type}</div>}- >- <Handle- type="source"- position={Position.Right}- id={`${props.id}-tool-output-handle`} // Add index to match store logic- className="my-right-handle"- />- <NodeSection title="Configuration">- <div className="text-sm">{config.description}</div>- </NodeSection>-- <NodeSection title="Content">- <div className="text-sm break-all">- <TruncatableText content={config.content || ""} textThreshold={150} />- </div>- </NodeSection>+ </>+ )}</BaseNode>);-};--// Termination Node+});-// First, let's add the Termination Node component-export const TerminationNode: React.FC<NodeProps<CustomNode>> = (props) => {- const config = props.data.config as TerminationConfig;-- return (- <BaseNode- {...props}- icon={iconMap.termination}- descriptionContent={<div>Type: {config.termination_type}</div>}- >- <Handle- type="source"- position={Position.Right}- id={`${props.id}-termination-output-handle`}- className="my-right-handle"- />-- <NodeSection title="Configuration">- <div className="text-sm">- {config.termination_type === "MaxMessageTermination" && (- <div>Max Messages: {config.max_messages}</div>- )}- {config.termination_type === "TextMentionTermination" && (- <div>Text: {config.text}</div>- )}- </div>- </NodeSection>- </BaseNode>- );-};+AgentNode.displayName = "AgentNode";// Export all node typesexport const nodeTypes = {team: TeamNode,agent: AgentNode,- model: ModelNode,- tool: ToolNode,- termination: TerminationNode,};const EDGE_STYLES = {- "model-connection": { stroke: "rgb(59, 130, 246)" },- "tool-connection": { stroke: "rgb(34, 197, 94)" },- "agent-connection": { stroke: "rgb(168, 85, 247)" },- "termination-connection": { stroke: "rgb(255, 159, 67)" },+ "model-connection": { stroke: "rgb(220,220,220)" },+ "tool-connection": { stroke: "rgb(220,220,220)" },+ "agent-connection": { stroke: "rgb(220,220,220)" },+ "termination-connection": { stroke: "rgb(220,220,220)" },} as const;type EdgeType = keyof typeof EDGE_STYLES;+type CustomEdgeProps = EdgeProps & {+ type: EdgeType;+};-export const CustomEdge = ({ data, ...props }: EdgeProps) => {+export const CustomEdge = ({+ type,+ data,+ deletable,+ ...props+}: CustomEdgeProps) => {const [edgePath] = getBezierPath(props);- const edgeType = (data?.type as EdgeType) || "model-connection";+ const edgeType = type || "model-connection";++ // Extract only the SVG path properties we want to pass+ const { style: baseStyle, ...pathProps } = props;+ const {+ // Filter out the problematic props+ sourceX,+ sourceY,+ sourcePosition,+ targetPosition,+ sourceHandleId,+ targetHandleId,+ pathOptions,+ selectable,+ ...validPathProps+ } = pathProps;return (<BaseEdgepath={edgePath}style={{ ...EDGE_STYLES[edgeType], strokeWidth: 2 }}- {...props}+ {...validPathProps}/>);};diff --git a/python/packages/autogen-studio/frontend/src/components/views/team/builder/store.tsx b/python/packages/autogen-studio/frontend/src/components/views/team/builder/store.tsxindex 9c591bdd8..dc6101ed3 100644--- a/python/packages/autogen-studio/frontend/src/components/views/team/builder/store.tsx+++ b/python/packages/autogen-studio/frontend/src/components/views/team/builder/store.tsx@@ -1,4 +1,5 @@import { create } from "zustand";+import { isEqual } from "lodash";import {CustomNode,CustomEdge,@@ -10,48 +11,40 @@ import { nanoid } from "nanoid";import {TeamConfig,AgentConfig,- ModelConfig,ToolConfig,- ComponentTypes,- ComponentConfigTypes,- TerminationConfig,+ Component,+ ComponentConfig,} from "../../../types/datamodel";-import { convertTeamConfigToGraph, getLayoutedElements } from "./utils";+import {+ convertTeamConfigToGraph,+ getLayoutedElements,+ getUniqueName,+} from "./utils";+import {+ isTeamComponent,+ isAgentComponent,+ isToolComponent,+ isTerminationComponent,+ isModelComponent,+ isSelectorTeam,+ isAssistantAgent,+} from "../../../types/guards";const MAX_HISTORY = 50;-const isTeamConfig = (config: any): config is TeamConfig => {- return "team_type" in config;-};--const isAgentConfig = (config: any): config is AgentConfig => {- return "agent_type" in config;-};--const isModelConfig = (config: any): config is ModelConfig => {- return "model_type" in config;-};--const isToolConfig = (config: any): config is ToolConfig => {- return "tool_type" in config;-};--const isTerminationConfig = (config: any): config is TerminationConfig => {- return "termination_type" in config;-};-export interface TeamBuilderState {nodes: CustomNode[];edges: CustomEdge[];selectedNodeId: string | null;history: Array<{ nodes: CustomNode[]; edges: CustomEdge[] }>;currentHistoryIndex: number;- originalConfig: TeamConfig | null;+ originalComponent: Component<TeamConfig> | null;++ // Simplified actionsaddNode: (- type: ComponentTypes,position: Position,- config: ComponentConfigTypes,- targetNodeId?: string+ component: Component<ComponentConfig>,+ targetNodeId: string) => void;updateNode: (nodeId: string, updates: Partial<NodeData>) => void;@@ -66,85 +59,39 @@ export interface TeamBuilderState {redo: () => void;// Sync with JSON- syncToJson: () => TeamConfig | null;- loadFromJson: (config: TeamConfig) => GraphState;+ syncToJson: () => Component<TeamConfig> | null;+ loadFromJson: (+ config: Component<TeamConfig>,+ isInitialLoad?: boolean+ ) => GraphState;layoutNodes: () => void;resetHistory: () => void;+ addToHistory: () => void;}-const buildTeamConfig = (+const buildTeamComponent = (teamNode: CustomNode,nodes: CustomNode[],edges: CustomEdge[]-): TeamConfig | null => {- if (!isTeamConfig(teamNode.data.config)) return null;-- const config = { ...teamNode.data.config };-- // Use edge queries instead of connections- const modelEdge = edges.find(- (e) => e.target === teamNode.id && e.type === "model-connection"- );- if (modelEdge) {- const modelNode = nodes.find((n) => n.id === modelEdge.source);- if (- modelNode &&- isModelConfig(modelNode.data.config) &&- config.team_type === "SelectorGroupChat"- ) {- config.model_client = modelNode.data.config;- }- }+): Component<TeamConfig> | null => {+ if (!isTeamComponent(teamNode.data.component)) return null;- // Add termination connection handling- const terminationEdge = edges.find(- (e) => e.target === teamNode.id && e.type === "termination-connection"- );- if (terminationEdge) {- const terminationNode = nodes.find((n) => n.id === terminationEdge.source);- if (terminationNode && isTerminationConfig(terminationNode.data.config)) {- config.termination_condition = terminationNode.data.config;- }- }+ const component = { ...teamNode.data.component };// Get participants using edgesconst participantEdges = edges.filter((e) => e.source === teamNode.id && e.type === "agent-connection");- config.participants = participantEdges+ component.config.participants = participantEdges.map((edge) => {const agentNode = nodes.find((n) => n.id === edge.target);- if (!agentNode || !isAgentConfig(agentNode.data.config)) return null;-- const agentConfig = { ...agentNode.data.config };-- // Get agent's model using edges- const agentModelEdge = edges.find(- (e) => e.target === edge.target && e.type === "model-connection"- );- if (agentModelEdge) {- const modelNode = nodes.find((n) => n.id === agentModelEdge.source);- if (modelNode && isModelConfig(modelNode.data.config)) {- agentConfig.model_client = modelNode.data.config;- }- }-- // Get agent's tools using edges- const toolEdges = edges.filter(- (e) => e.target === edge.target && e.type === "tool-connection"- );- agentConfig.tools = toolEdges- .map((toolEdge) => {- const toolNode = nodes.find((n) => n.id === toolEdge.source);- return toolNode?.data.config as ToolConfig;- })- .filter((tool): tool is ToolConfig => tool !== null);-- return agentConfig;+ if (!agentNode || !isAgentComponent(agentNode.data.component))+ return null;+ return agentNode.data.component;})- .filter((agent): agent is AgentConfig => agent !== null);+ .filter((agent): agent is Component<AgentConfig> => agent !== null);- return config;+ return component;};export const useTeamBuilderStore = create<TeamBuilderState>((set, get) => ({@@ -153,191 +100,181 @@ export const useTeamBuilderStore = create<TeamBuilderState>((set, get) => ({selectedNodeId: null,history: [],currentHistoryIndex: -1,- originalConfig: null,+ originalComponent: null,addNode: (- type: ComponentTypes,position: Position,- config: ComponentConfigTypes,- targetNodeId?: string+ component: Component<ComponentConfig>,+ targetNodeId: string) => {set((state) => {- // Determine label based on config type- let label = "";- if (isTeamConfig(config)) {- label = config.name || "Team";- } else if (isAgentConfig(config)) {- label = config.name || "Agent";- } else if (isModelConfig(config)) {- label = config.model || "Model";- } else if (isToolConfig(config)) {- label = config.name || "Tool";- } else if (isTerminationConfig(config)) {- label = config.termination_type || "Termination";- }-- // Create new node without connections object- const newNode: CustomNode = {- id: nanoid(),- type,- position,- data: {- label: label || "Node",- type,- config,- },- };-+ // Deep clone the incoming component to avoid reference issues+ const clonedComponent = JSON.parse(JSON.stringify(component));let newNodes = [...state.nodes];let newEdges = [...state.edges];if (targetNodeId) {const targetNode = state.nodes.find((n) => n.id === targetNodeId);- if (targetNode) {+ // console.log("Target node", targetNode);+ if (!targetNode) return state;++ // Handle configuration updates based on component type+ if (isModelComponent(clonedComponent)) {if (- type === "model" &&- ["team", "agent"].includes(targetNode.data.type)+ isTeamComponent(targetNode.data.component) &&+ isSelectorTeam(targetNode.data.component)) {- // Find existing model connection and node- const existingModelEdge = newEdges.find(- (edge) =>- edge.target === targetNodeId && edge.type === "model-connection"- );-- if (existingModelEdge) {- // Remove the existing model node- const existingModelNodeId = existingModelEdge.source;- newNodes = newNodes.filter(- (node) => node.id !== existingModelNodeId- );-- // Remove all edges connected to the old model node- newEdges = newEdges.filter(- (edge) =>- edge.source !== existingModelNodeId &&- edge.target !== existingModelNodeId- );- }-- // Add the new model node- newNodes.push(newNode);-- // Add new model connection- newEdges.push({- id: nanoid(),- source: newNode.id,- target: targetNodeId,- sourceHandle: `${newNode.id}-model-output-handle`,- targetHandle: `${targetNodeId}-model-input-handle`,- type: "model-connection",- });-- // Update config- if (- isTeamConfig(targetNode.data.config) &&- isModelConfig(config) &&- targetNode.data.config.team_type === "SelectorGroupChat"- ) {- targetNode.data.config.model_client = config;- } else if (- isAgentConfig(targetNode.data.config) &&- isModelConfig(config)- ) {- targetNode.data.config.model_client = config;- }+ targetNode.data.component.config.model_client = clonedComponent;+ return {+ nodes: newNodes,+ edges: newEdges,+ history: [+ ...state.history.slice(0, state.currentHistoryIndex + 1),+ { nodes: newNodes, edges: newEdges },+ ].slice(-MAX_HISTORY),+ currentHistoryIndex: state.currentHistoryIndex + 1,+ };} else if (- type === "termination" &&- targetNode.data.type === "team"+ isAgentComponent(targetNode.data.component) &&+ isAssistantAgent(targetNode.data.component)) {- // Find existing termination connection and node- const existingTerminationEdge = newEdges.find(- (edge) =>- edge.target === targetNodeId &&- edge.type === "termination-connection"- );-- if (existingTerminationEdge) {- // Remove the existing termination node- const existingTerminationNodeId = existingTerminationEdge.source;- newNodes = newNodes.filter(- (node) => node.id !== existingTerminationNodeId- );-- // Remove all edges connected to the old termination node- newEdges = newEdges.filter(- (edge) =>- edge.source !== existingTerminationNodeId &&- edge.target !== existingTerminationNodeId- );+ targetNode.data.component.config.model_client = clonedComponent;+ return {+ nodes: newNodes,+ edges: newEdges,+ history: [+ ...state.history.slice(0, state.currentHistoryIndex + 1),+ { nodes: newNodes, edges: newEdges },+ ].slice(-MAX_HISTORY),+ currentHistoryIndex: state.currentHistoryIndex + 1,+ };+ }+ } else if (isToolComponent(clonedComponent)) {+ if (+ isAgentComponent(targetNode.data.component) &&+ isAssistantAgent(targetNode.data.component)+ ) {+ if (!targetNode.data.component.config.tools) {+ targetNode.data.component.config.tools = [];}-- // Add the new termination node- newNodes.push(newNode);-- // Add new termination connection- newEdges.push({- id: nanoid(),- source: newNode.id,- target: targetNodeId,- sourceHandle: `${newNode.id}-termination-output-handle`,- targetHandle: `${targetNodeId}-termination-input-handle`,- type: "termination-connection",+ const toolName = getUniqueName(+ clonedComponent.config.name,+ targetNode.data.component.config.tools.map((t) => t.config.name)+ );+ clonedComponent.config.name = toolName;+ targetNode.data.component.config.tools.push(clonedComponent);+ return {+ nodes: newNodes,+ edges: newEdges,+ history: [+ ...state.history.slice(0, state.currentHistoryIndex + 1),+ { nodes: newNodes, edges: newEdges },+ ].slice(-MAX_HISTORY),+ currentHistoryIndex: state.currentHistoryIndex + 1,+ };+ }+ } else if (isTerminationComponent(clonedComponent)) {+ console.log("Termination component added", clonedComponent);+ if (isTeamComponent(targetNode.data.component)) {+ newNodes = state.nodes.map((node) => {+ if (node.id === targetNodeId) {+ return {+ ...node,+ data: {+ ...node.data,+ component: {+ ...node.data.component,+ config: {+ ...node.data.component.config,+ termination_condition: clonedComponent,+ },+ },+ },+ };+ }+ return node;});- // Update config- if (- isTeamConfig(targetNode.data.config) &&- isTerminationConfig(config)- ) {- targetNode.data.config.termination_condition = config;- }- } else if (type === "tool" && targetNode.data.type === "agent") {- // Add tool connection- newNodes.push(newNode);- newEdges.push({- id: nanoid(),- source: newNode.id,- target: targetNodeId,- sourceHandle: `${newNode.id}-tool-output-handle`,- targetHandle: `${targetNodeId}-tool-input-handle`,- type: "tool-connection",- });+ return {+ nodes: newNodes,+ edges: newEdges,+ history: [+ ...state.history.slice(0, state.currentHistoryIndex + 1),+ { nodes: newNodes, edges: newEdges },+ ].slice(-MAX_HISTORY),+ currentHistoryIndex: state.currentHistoryIndex + 1,+ };+ }+ }+ }- // Update config- if (isAgentConfig(targetNode.data.config) && isToolConfig(config)) {- if (!targetNode.data.config.tools) {- targetNode.data.config.tools = [];- }- targetNode.data.config.tools.push(config);- }- } else if (type === "agent" && targetNode.data.type === "team") {- // Add agent connection- newNodes.push(newNode);- newEdges.push({- id: nanoid(),- source: targetNodeId,- target: newNode.id,- sourceHandle: `${targetNodeId}-agent-output-handle`,- targetHandle: `${newNode.id}-agent-input-handle`,- type: "agent-connection",- });+ // Handle team and agent nodes+ if (isTeamComponent(clonedComponent)) {+ const newNode: CustomNode = {+ id: nanoid(),+ position,+ type: clonedComponent.component_type,+ data: {+ label: clonedComponent.label || "Team",+ component: clonedComponent,+ type: clonedComponent.component_type as NodeData["type"],+ },+ };+ newNodes.push(newNode);+ } else if (isAgentComponent(clonedComponent)) {+ // Find the team node to connect to+ const teamNode = newNodes.find((n) =>+ isTeamComponent(n.data.component)+ );+ if (teamNode) {+ // Ensure unique agent name+ if (+ isAssistantAgent(clonedComponent) &&+ isTeamComponent(teamNode.data.component)+ ) {+ const existingAgents =+ teamNode.data.component.config.participants || [];+ const existingNames = existingAgents.map((p) => p.config.name);+ clonedComponent.config.name = getUniqueName(+ clonedComponent.config.name,+ existingNames+ );+ }- // Update config- if (isTeamConfig(targetNode.data.config) && isAgentConfig(config)) {- if (!targetNode.data.config.participants) {- targetNode.data.config.participants = [];- }- targetNode.data.config.participants.push(config);+ const newNode: CustomNode = {+ id: nanoid(),+ position,+ type: clonedComponent.component_type,+ data: {+ label: clonedComponent.label || clonedComponent.config.name,+ component: clonedComponent,+ type: clonedComponent.component_type as NodeData["type"],+ },+ };++ newNodes.push(newNode);++ // Add connection to team+ newEdges.push({+ id: nanoid(),+ source: teamNode.id,+ target: newNode.id,+ sourceHandle: `${teamNode.id}-agent-output-handle`,+ targetHandle: `${newNode.id}-agent-input-handle`,+ type: "agent-connection",+ });++ // Update team's participants+ if (isTeamComponent(teamNode.data.component)) {+ if (!teamNode.data.component.config.participants) {+ teamNode.data.component.config.participants = [];}- } else {- // For all other cases, just add the new node- newNodes.push(newNode);+ teamNode.data.component.config.participants.push(+ newNode.data.component as Component<AgentConfig>+ );}}- } else {- // If no target node, just add the new node- newNodes.push(newNode);}const { nodes: layoutedNodes, edges: layoutedEdges } =@@ -358,72 +295,53 @@ export const useTeamBuilderStore = create<TeamBuilderState>((set, get) => ({updateNode: (nodeId: string, updates: Partial<NodeData>) => {set((state) => {const newNodes = state.nodes.map((node) => {- if (node.id !== nodeId) return node;+ if (node.id !== nodeId) {+ // If this isn't the directly updated node, check if it needs related updates+ const isTeamWithUpdatedAgent =+ isTeamComponent(node.data.component) &&+ state.edges.some(+ (e) =>+ e.type === "agent-connection" &&+ e.target === nodeId &&+ e.source === node.id+ );++ if (isTeamWithUpdatedAgent && isTeamComponent(node.data.component)) {+ return {+ ...node,+ data: {+ ...node.data,+ component: {+ ...node.data.component,+ config: {+ ...node.data.component.config,+ participants: node.data.component.config.participants.map(+ (participant) =>+ participant ===+ state.nodes.find((n) => n.id === nodeId)?.data.component+ ? updates.component+ : participant+ ),+ },+ },+ },+ };+ }+ return node;+ }- // Update the node with new data- const updatedNode = {+ // This is the directly updated node+ const updatedComponent = updates.component || node.data.component;+ return {...node,data: {...node.data,...updates,- // Update label based on config type- label: (() => {- const config = { ...node.data.config, ...updates.config };- if (isTeamConfig(config)) return config.name || "Team";- if (isAgentConfig(config)) return config.name || "Agent";- if (isModelConfig(config)) return config.model || "Model";- if (isToolConfig(config)) return config.name || "Tool";- if (isTerminationConfig(config))- return config.termination_type || "Termination";- return node.data.label;- })(),+ component: updatedComponent,},};-- return updatedNode;});- // Update related nodes' configs- const updatedNode = newNodes.find((n) => n.id === nodeId);- if (!updatedNode) return state;-- // If an agent was updated, update its parent team's participants- if (updatedNode.data.type === "agent") {- const teamEdge = state.edges.find(- (e) => e.type === "agent-connection" && e.target === nodeId- );- if (teamEdge) {- newNodes.forEach((node) => {- if (node.id === teamEdge.source && isTeamConfig(node.data.config)) {- const agentConfig = updatedNode.data.config as AgentConfig;- node.data.config.participants = node.data.config.participants.map(- (p) => (p.name === agentConfig.name ? agentConfig : p)- );- }- });- }- }-- // If a tool was updated, update its parent agent's tools- if (updatedNode.data.type === "tool") {- const agentEdge = state.edges.find(- (e) => e.type === "tool-connection" && e.source === nodeId- );- if (agentEdge) {- newNodes.forEach((node) => {- if (- node.id === agentEdge.target &&- isAgentConfig(node.data.config)- ) {- const toolConfig = updatedNode.data.config as ToolConfig;- node.data.config.tools = node.data.config.tools?.map((t) =>- t.name === toolConfig.name ? toolConfig : t- );- }- });- }- }-return {nodes: newNodes,history: [@@ -438,6 +356,7 @@ export const useTeamBuilderStore = create<TeamBuilderState>((set, get) => ({removeNode: (nodeId: string) => {set((state) => {const nodesToRemove = new Set<string>();+ const updatedNodes = new Map<string, CustomNode>();const collectNodesToRemove = (id: string) => {const node = state.nodes.find((n) => n.id === id);@@ -450,72 +369,37 @@ export const useTeamBuilderStore = create<TeamBuilderState>((set, get) => ({(edge) => edge.source === id || edge.target === id);- // Handle cascading deletes based on node type- if (node.data.type === "team") {- // Find and remove all agents+ // Handle cascading deletes based on component type+ if (isTeamComponent(node.data.component)) {+ // Find and remove all connected agentsconnectedEdges.filter((e) => e.type === "agent-connection").forEach((e) => collectNodesToRemove(e.target));-- // Remove team's model if exists- connectedEdges- .filter((e) => e.type === "model-connection")- .forEach((e) => collectNodesToRemove(e.source));-- // Remove termination condition if exists- connectedEdges- .filter((e) => e.type === "termination-connection")- .forEach((e) => collectNodesToRemove(e.source));- } else if (node.data.type === "agent") {- // Remove agent's model if exists- connectedEdges- .filter((e) => e.type === "model-connection")- .forEach((e) => collectNodesToRemove(e.source));-- // Remove all agent's tools- connectedEdges- .filter((e) => e.type === "tool-connection")- .forEach((e) => collectNodesToRemove(e.source));-- // Also need to remove agent from team's config+ } else if (isAgentComponent(node.data.component)) {+ // Update team's participants if agent is connected to a teamconst teamEdge = connectedEdges.find((e) => e.type === "agent-connection");if (teamEdge) {const teamNode = state.nodes.find((n) => n.id === teamEdge.source);- if (teamNode && isTeamConfig(teamNode.data.config)) {- const agentConfig = node.data.config as AgentConfig;- teamNode.data.config.participants =- teamNode.data.config.participants.filter(- (p) => p.name !== agentConfig.name- );- }- }- } else if (node.data.type === "tool") {- // Update agent's tools array when removing a tool- const agentEdge = connectedEdges.find(- (e) => e.type === "tool-connection"- );- if (agentEdge) {- const agentNode = state.nodes.find(- (n) => n.id === agentEdge.target- );- if (agentNode && isAgentConfig(agentNode.data.config)) {- const toolConfig = node.data.config as ToolConfig;- agentNode.data.config.tools = agentNode.data.config.tools?.filter(- (t) => t.name !== toolConfig.name- );- }- }- } else if (node.data.type === "termination") {- // Update team's termination condition when removing it- const teamEdge = connectedEdges.find(- (e) => e.type === "termination-connection"- );- if (teamEdge) {- const teamNode = state.nodes.find((n) => n.id === teamEdge.target);- if (teamNode && isTeamConfig(teamNode.data.config)) {- teamNode.data.config.termination_condition = undefined;+ if (teamNode && isTeamComponent(teamNode.data.component)) {+ const updatedTeamNode = {+ ...teamNode,+ data: {+ ...teamNode.data,+ component: {+ ...teamNode.data.component,+ config: {+ ...teamNode.data.component.config,+ participants:+ teamNode.data.component.config.participants.filter(+ (p) => !isEqual(p, node.data.component)+ ),+ },+ },+ },+ };+ updatedNodes.set(teamNode.id, updatedTeamNode);}}}@@ -524,10 +408,10 @@ export const useTeamBuilderStore = create<TeamBuilderState>((set, get) => ({// Start the cascade deletion from the initial nodecollectNodesToRemove(nodeId);- // Remove all collected nodes- const newNodes = state.nodes.filter(- (node) => !nodesToRemove.has(node.id)- );+ // Create new nodes array with both removals and updates+ const newNodes = state.nodes+ .filter((node) => !nodesToRemove.has(node.id))+ .map((node) => updatedNodes.get(node.id) || node);// Remove all affected edgesconst newEdges = state.edges.filter(@@ -548,41 +432,28 @@ export const useTeamBuilderStore = create<TeamBuilderState>((set, get) => ({},addEdge: (edge: CustomEdge) => {- set((state) => {- let newEdges = [...state.edges];-- if (edge.type === "model-connection") {- newEdges = newEdges.filter(- (e) => !(e.target === edge.target && e.type === "model-connection")- );- }-- newEdges.push(edge);-- return {- edges: newEdges,- history: [- ...state.history.slice(0, state.currentHistoryIndex + 1),- { nodes: state.nodes, edges: newEdges },- ].slice(-MAX_HISTORY),- currentHistoryIndex: state.currentHistoryIndex + 1,- };- });+ set((state) => ({+ edges: [...state.edges, edge],+ history: [+ ...state.history.slice(0, state.currentHistoryIndex + 1),+ { nodes: state.nodes, edges: [...state.edges, edge] },+ ].slice(-MAX_HISTORY),+ currentHistoryIndex: state.currentHistoryIndex + 1,+ }));},removeEdge: (edgeId: string) => {- set((state) => {- const newEdges = state.edges.filter((edge) => edge.id !== edgeId);-- return {- edges: newEdges,- history: [- ...state.history.slice(0, state.currentHistoryIndex + 1),- { nodes: state.nodes, edges: newEdges },- ].slice(-MAX_HISTORY),- currentHistoryIndex: state.currentHistoryIndex + 1,- };- });+ set((state) => ({+ edges: state.edges.filter((edge) => edge.id !== edgeId),+ history: [+ ...state.history.slice(0, state.currentHistoryIndex + 1),+ {+ nodes: state.nodes,+ edges: state.edges.filter((edge) => edge.id !== edgeId),+ },+ ].slice(-MAX_HISTORY),+ currentHistoryIndex: state.currentHistoryIndex + 1,+ }));},setSelectedNode: (nodeId: string | null) => {@@ -619,11 +490,13 @@ export const useTeamBuilderStore = create<TeamBuilderState>((set, get) => ({syncToJson: () => {const state = get();- const teamNodes = state.nodes.filter((node) => node.data.type === "team");+ const teamNodes = state.nodes.filter(+ (node) => node.data.component.component_type === "team"+ );if (teamNodes.length === 0) return null;const teamNode = teamNodes[0];- return buildTeamConfig(teamNode, state.nodes, state.edges);+ return buildTeamComponent(teamNode, state.nodes, state.edges);},layoutNodes: () => {@@ -644,30 +517,63 @@ export const useTeamBuilderStore = create<TeamBuilderState>((set, get) => ({});},- loadFromJson: (config: TeamConfig) => {+ loadFromJson: (+ config: Component<TeamConfig>,+ isInitialLoad: boolean = true+ ) => {+ // Get graph representation of team configconst { nodes, edges } = convertTeamConfigToGraph(config);const { nodes: layoutedNodes, edges: layoutedEdges } = getLayoutedElements(nodes,edges);- set((state) => {- return {+ if (isInitialLoad) {+ // Initial load - reset history+ set({nodes: layoutedNodes,edges: layoutedEdges,- originalConfig: config,- history: [{ nodes: layoutedNodes, edges: layoutedEdges }], // Reset history- currentHistoryIndex: 0, // Reset to 0+ originalComponent: config,+ history: [{ nodes: layoutedNodes, edges: layoutedEdges }],+ currentHistoryIndex: 0,selectedNodeId: null,- };- });+ });+ } else {+ // JSON edit - check if state actually changed+ const currentState = get();+ if (+ !isEqual(layoutedNodes, currentState.nodes) ||+ !isEqual(layoutedEdges, currentState.edges)+ ) {+ set((state) => ({+ nodes: layoutedNodes,+ edges: layoutedEdges,+ history: [+ ...state.history.slice(0, state.currentHistoryIndex + 1),+ { nodes: layoutedNodes, edges: layoutedEdges },+ ].slice(-MAX_HISTORY),+ currentHistoryIndex: state.currentHistoryIndex + 1,+ }));+ }+ }return { nodes: layoutedNodes, edges: layoutedEdges };},+resetHistory: () => {set((state) => ({history: [{ nodes: state.nodes, edges: state.edges }],currentHistoryIndex: 0,}));},++ addToHistory: () => {+ set((state) => ({+ history: [+ ...state.history.slice(0, state.currentHistoryIndex + 1),+ { nodes: state.nodes, edges: state.edges },+ ].slice(-MAX_HISTORY),+ currentHistoryIndex: state.currentHistoryIndex + 1,+ }));+ },}));diff --git a/python/packages/autogen-studio/frontend/src/components/views/team/builder/types.ts b/python/packages/autogen-studio/frontend/src/components/views/team/builder/types.tsindex ca96204c9..d767bc29f 100644--- a/python/packages/autogen-studio/frontend/src/components/views/team/builder/types.ts+++ b/python/packages/autogen-studio/frontend/src/components/views/team/builder/types.ts@@ -1,10 +1,19 @@+// builder/types.tsimport { Node, Edge } from "@xyflow/react";-import { ComponentConfigTypes, ComponentTypes } from "../../../types/datamodel";+import {+ Component,+ ComponentConfig,+ ComponentTypes,+} from "../../../types/datamodel";export interface NodeData extends Record<string, unknown> {- label: string;- type: ComponentTypes;- config: ComponentConfigTypes;+ component: Component<ComponentConfig>;+}++export interface EditingState {+ component: Component<ComponentConfig>;+ path: string[];+ changes?: Partial<Component<ComponentConfig>>;}// Define our node type that extends the XYFlow Node type@@ -41,8 +50,7 @@ export interface FormFieldMapping {}export interface DragItem {- type: ComponentTypes;- config: ComponentConfigTypes;+ config: ComponentConfig;}export interface NodeComponentProps {@@ -54,6 +62,7 @@ export interface NodeComponentProps {export interface NodeEditorProps {node: CustomNode | null;onUpdate: (updates: Partial<NodeData>) => void;+ onClose: () => void;}export interface LibraryProps {diff --git a/python/packages/autogen-studio/frontend/src/components/views/team/builder/utils.ts b/python/packages/autogen-studio/frontend/src/components/views/team/builder/utils.tsindex 6e5c70931..0196217f0 100644--- a/python/packages/autogen-studio/frontend/src/components/views/team/builder/utils.ts+++ b/python/packages/autogen-studio/frontend/src/components/views/team/builder/utils.ts@@ -1,66 +1,167 @@-import dagre from "@dagrejs/dagre";-import { CustomNode, CustomEdge } from "./types";import { nanoid } from "nanoid";import {TeamConfig,- ModelConfig,+ Component,+ ComponentConfig,AgentConfig,- ToolConfig,- ComponentTypes,- TerminationConfig,} from "../../../types/datamodel";--interface ConversionResult {- nodes: CustomNode[];- edges: CustomEdge[];-}+import {+ isAssistantAgent,+ isUserProxyAgent,+ isWebSurferAgent,+} from "../../../types/guards";+import { CustomNode, CustomEdge } from "./types";interface Position {x: number;y: number;}-// Calculate positions for participants in a grid layout-const calculateParticipantPosition = (+interface NodeDimensions {+ width: number;+ height: number;+}++// Updated layout configuration with dynamic height handling+const LAYOUT_CONFIG = {+ TEAM_NODE: {+ X_POSITION: 100,+ MIN_Y_POSITION: 200,+ },+ AGENT: {+ START_X: 600,+ START_Y: 200,+ X_STAGGER: 0,+ MIN_Y_STAGGER: 50, // Minimum vertical space between nodes+ },+ NODE: {+ WIDTH: 272,+ MIN_HEIGHT: 100,+ PADDING: 20,+ },+ // Estimated heights for different node contents+ CONTENT_HEIGHTS: {+ BASE: 80, // Header + basic info+ DESCRIPTION: 60,+ MODEL_SECTION: 100,+ TOOL_SECTION: 80,+ TOOL_ITEM: 40,+ AGENT_SECTION: 80,+ AGENT_ITEM: 40,+ TERMINATION_SECTION: 80,+ },+};++// Calculate estimated node height based on content+const calculateNodeHeight = (component: Component<ComponentConfig>): number => {+ let height = LAYOUT_CONFIG.CONTENT_HEIGHTS.BASE;++ // Add height for description if present+ if (component.description) {+ height += LAYOUT_CONFIG.CONTENT_HEIGHTS.DESCRIPTION;+ }++ // Add heights for specific component types+ switch (component.component_type) {+ case "team":+ const teamConfig = component as Component<TeamConfig>;+ // Add height for agents section+ if (teamConfig.config.participants?.length) {+ height += LAYOUT_CONFIG.CONTENT_HEIGHTS.AGENT_SECTION;+ height +=+ teamConfig.config.participants.length *+ LAYOUT_CONFIG.CONTENT_HEIGHTS.AGENT_ITEM;+ }+ // Add height for termination section if present+ if (teamConfig.config.termination_condition) {+ height += LAYOUT_CONFIG.CONTENT_HEIGHTS.TERMINATION_SECTION;+ }+ break;++ case "agent":+ // Only AssistantAgent has model_client and tools+ if (isAssistantAgent(component)) {+ height += 200;+ // Add height for tools section and items+ if (component.config.tools?.length) {+ height += LAYOUT_CONFIG.CONTENT_HEIGHTS.TOOL_SECTION;+ height +=+ component.config.tools.length *+ LAYOUT_CONFIG.CONTENT_HEIGHTS.TOOL_ITEM;+ }+ }+ if (isWebSurferAgent(component)) {+ height += 100;+ }++ if (isUserProxyAgent(component)) {+ height += -100;+ }++ break;+ }++ return Math.max(height, LAYOUT_CONFIG.NODE.MIN_HEIGHT);+};++// Calculate position for an agent node considering previous nodes' heights+const calculateAgentPosition = (index: number,- totalParticipants: number+ previousNodes: CustomNode[]): Position => {- const GRID_SPACING = 250;- const PARTICIPANTS_PER_ROW = 3;+ const previousNodeHeights = previousNodes.map(+ (node) => calculateNodeHeight(node.data.component) + 50+ );++ const totalPreviousHeight = previousNodeHeights.reduce(+ (sum, height) => sum + height + LAYOUT_CONFIG.AGENT.MIN_Y_STAGGER,+ 0+ );++ return {+ x: LAYOUT_CONFIG.AGENT.START_X + index * LAYOUT_CONFIG.AGENT.X_STAGGER,+ y: LAYOUT_CONFIG.AGENT.START_Y + totalPreviousHeight,+ };+};- const row = Math.floor(index / PARTICIPANTS_PER_ROW);- const col = index % PARTICIPANTS_PER_ROW;+// Calculate team node position based on connected agents+const calculateTeamPosition = (agentNodes: CustomNode[]): Position => {+ if (agentNodes.length === 0) {+ return {+ x: LAYOUT_CONFIG.TEAM_NODE.X_POSITION,+ y: LAYOUT_CONFIG.TEAM_NODE.MIN_Y_POSITION,+ };+ }++ // Calculate the average Y position of all agent nodes+ const totalY = agentNodes.reduce((sum, node) => sum + node.position.y, 0);+ const averageY = totalY / agentNodes.length;++ // Ensure minimum Y position+ const y = Math.max(LAYOUT_CONFIG.TEAM_NODE.MIN_Y_POSITION, averageY);return {- x: col * GRID_SPACING,- y: (row + 1) * GRID_SPACING,+ x: LAYOUT_CONFIG.TEAM_NODE.X_POSITION,+ y,};};-// Helper to create nodes with consistent structure+// Helper to create nodes with consistent structure and dynamic heightconst createNode = (- type: ComponentTypes,position: Position,- config:- | TeamConfig- | ModelConfig- | AgentConfig- | ToolConfig- | TerminationConfig,+ component: Component<ComponentConfig>,label?: string): CustomNode => ({id: nanoid(),- type,position,+ type: component.component_type,data: {- label: label || type,- type,- config,- connections: {- modelClient: null,- tools: [],- participants: [],- termination: null,+ label: label || component.label || component.component_type,+ component,+ type: component.component_type,+ dimensions: {+ width: LAYOUT_CONFIG.NODE.WIDTH,+ height: calculateNodeHeight(component),},},});@@ -69,229 +170,100 @@ const createNode = (const createEdge = (source: string,target: string,- type:- | "model-connection"- | "tool-connection"- | "agent-connection"- | "team-connection"- | "termination-connection"+ type: "agent-connection"): CustomEdge => ({id: `e${source}-${target}`,source,target,+ sourceHandle: `${source}-agent-output-handle`,+ targetHandle: `${target}-agent-input-handle`,type,});+// Convert team configuration to graph structure with dynamic layoutexport const convertTeamConfigToGraph = (- config: TeamConfig-): ConversionResult => {+ teamComponent: Component<TeamConfig>+): { nodes: CustomNode[]; edges: CustomEdge[] } => {const nodes: CustomNode[] = [];const edges: CustomEdge[] = [];- // Create team node- const teamNode = createNode(- "team",- { x: 400, y: 50 },- {- ...config,- // participants: [], // Clear participants as we'll rebuild from edges- }- );- nodes.push(teamNode);-- // Add model client if present- if (config.team_type === "SelectorGroupChat" && config.model_client) {- const modelNode = createNode(- "model",- { x: 200, y: 50 },- config.model_client,- config.model_client.model- );- nodes.push(modelNode);- edges.push({- id: nanoid(),- source: modelNode.id,- target: teamNode.id,- sourceHandle: `${modelNode.id}-model-output-handle`,- targetHandle: `${teamNode.id}-model-input-handle`,- type: "model-connection",- });- }-- // Add participants (agents)- config.participants.forEach((participant, index) => {- const position = calculateParticipantPosition(- index,- config.participants.length- );- const agentNode = createNode("agent", position, {- ...participant,- // tools: [], // Clear tools as we'll rebuild from edges- });- nodes.push(agentNode);-- // Connect to team- edges.push({- id: nanoid(),- source: teamNode.id,- target: agentNode.id,- sourceHandle: `${teamNode.id}-agent-output-handle`,- targetHandle: `${agentNode.id}-agent-input-handle`,- type: "agent-connection",- });-- // Add agent's model client if present- if (participant.model_client) {- const agentModelNode = createNode(- "model",- {- x: position.x - 150,- y: position.y,- },- participant.model_client,- participant.model_client.model- );- nodes.push(agentModelNode);- edges.push({- id: nanoid(),- source: agentModelNode.id,- target: agentNode.id,- sourceHandle: `${agentModelNode.id}-model-output-handle`,- targetHandle: `${agentNode.id}-model-input-handle`,- type: "model-connection",- });- }-- // Add agent's tools- participant.tools?.forEach((tool, toolIndex) => {- const toolNode = createNode(- "tool",- {- x: position.x + 150,- y: position.y + toolIndex * 100,- },- tool- );- nodes.push(toolNode);- edges.push({- id: nanoid(),- source: toolNode.id,- target: agentNode.id,- sourceHandle: `${toolNode.id}-tool-output-handle`,- targetHandle: `${agentNode.id}-tool-input-handle`,- type: "tool-connection",- });- });+ // Create agent nodes first to calculate their positions+ const agentNodes: CustomNode[] = [];+ teamComponent.config.participants.forEach((participant, index) => {+ const position = calculateAgentPosition(index, agentNodes);+ const agentNode = createNode(position, participant);+ agentNodes.push(agentNode);});- // Add termination condition if present- if (config?.termination_condition) {- const terminationNode = createNode(- "termination",- { x: 600, y: 50 },- config.termination_condition- );- nodes.push(terminationNode);- edges.push({- id: nanoid(),- source: terminationNode.id,- target: teamNode.id,- sourceHandle: `${terminationNode.id}-termination-output-handle`,- targetHandle: `${teamNode.id}-termination-input-handle`,- type: "termination-connection",- });- }+ // Create team node with position based on agent positions+ const teamNode = createNode(calculateTeamPosition(agentNodes), teamComponent);++ // Add all nodes and create edges+ nodes.push(teamNode, ...agentNodes);+ agentNodes.forEach((agentNode) => {+ edges.push(createEdge(teamNode.id, agentNode.id, "agent-connection"));+ });return { nodes, edges };};-const NODE_WIDTH = 272;-const NODE_HEIGHT = 200;-+// Layout existing nodes with dynamic heightsexport const getLayoutedElements = (nodes: CustomNode[],edges: CustomEdge[]-) => {- const g = new dagre.graphlib.Graph();- const calculateRank = (node: CustomNode) => {- if (node.data.type === "model") {- // Check if this model is connected to a team or agent- const isTeamModel = edges.some(- (e) =>- e.source === node.id &&- nodes.find((n) => n.id === e.target)?.data.type === "team"- );- return isTeamModel ? 0 : 2;- }-- switch (node.data.type) {- case "team":- return 1;- case "agent":- return 3;- case "tool":- return 4;- case "termination":- return 1; // Same rank as team- default:- return 0;- }- };-- g.setGraph({- rankdir: "LR",- nodesep: 250,- ranksep: 150,- ranker: "network-simplex", // or "tight-tree" depending on needs- align: "DL",- });- g.setDefaultEdgeLabel(() => ({}));-- // Add nodes to the graph with their dimensions- nodes.forEach((node) => {- const rank = calculateRank(node);- g.setNode(node.id, {- width: NODE_WIDTH,- height: NODE_HEIGHT,- rank,- });- });+): { nodes: CustomNode[]; edges: CustomEdge[] } => {+ // Find team node and agent nodes+ const teamNode = nodes.find((n) => n.data.type === "team");+ if (!teamNode) return { nodes, edges };- // Add edges to the graph- edges.forEach((edge) => {- g.setEdge(edge.source, edge.target);- });+ const agentNodes = nodes.filter((n) => n.data.type !== "team");- // Apply the layout- dagre.layout(g);+ // Calculate new positions for agent nodes+ const layoutedAgentNodes = agentNodes.map((node, index) => ({+ ...node,+ position: calculateAgentPosition(index, agentNodes.slice(0, index)),+ data: {+ ...node.data,+ dimensions: {+ width: LAYOUT_CONFIG.NODE.WIDTH,+ height: calculateNodeHeight(node.data.component),+ },+ },+ }));- // Get the laid out nodes with their new positions- const layoutedNodes = nodes.map((node) => {- const nodeWithPosition = g.node(node.id);- return {- ...node,- position: {- x: nodeWithPosition.x - NODE_WIDTH / 2,- y: nodeWithPosition.y - NODE_HEIGHT / 2,+ // Update team node position+ const layoutedTeamNode = {+ ...teamNode,+ position: calculateTeamPosition(layoutedAgentNodes),+ data: {+ ...teamNode.data,+ dimensions: {+ width: LAYOUT_CONFIG.NODE.WIDTH,+ height: calculateNodeHeight(teamNode.data.component),},- };- });+ },+ };- return { nodes: layoutedNodes, edges };+ return {+ nodes: [layoutedTeamNode, ...layoutedAgentNodes],+ edges,+ };};-export const getNodeConnections = (nodeId: string, edges: CustomEdge[]) => {- return {- modelClient:- edges.find((e) => e.target === nodeId && e.type === "model-connection")- ?.source || null,+// Generate unique names (unchanged)+export const getUniqueName = (+ baseName: string,+ existingNames: string[]+): string => {+ let validBaseName = baseName+ .replace(/[^a-zA-Z0-9_$]/g, "_")+ .replace(/^([^a-zA-Z_$])/, "_$1");- tools: edges- .filter((e) => e.target === nodeId && e.type === "tool-connection")- .map((e) => e.source),+ if (!existingNames.includes(validBaseName)) return validBaseName;- participants: edges- .filter((e) => e.source === nodeId && e.type === "agent-connection")- .map((e) => e.target),- };+ let counter = 1;+ while (existingNames.includes(`${validBaseName}_${counter}`)) {+ counter++;+ }+ return `${validBaseName}_${counter}`;};diff --git a/python/packages/autogen-studio/frontend/src/components/views/team/hooks.tsx b/python/packages/autogen-studio/frontend/src/components/views/team/hooks.tsxnew file mode 100644index 000000000..8079a6068--- /dev/null+++ b/python/packages/autogen-studio/frontend/src/components/views/team/hooks.tsx@@ -0,0 +1,39 @@+import { config } from "process";+import { Team } from "../../types/datamodel";++export const useTeam = (team: Team) => {+ return {+ id: team.id,+ name: team.config.config.name,+ type: team.config.config.team_type,+ participants: team.config.config.participants,+ updated: team.updated_at,+ config: team.config,++ // Helper methods+ setName: (name: string) => {+ team.config.config.name = name;+ },++ // Computed properties+ agentCount: team.config.config.participants.length,++ // Type guards+ isRoundRobin: () => team.config.config.team_type === "RoundRobinGroupChat",+ isSelector: () => team.config.config.team_type === "SelectorGroupChat",+ };+};++// For creating new teams+export const useTeamCreation = () => {+ const createTeamName = () => `new_team_${new Date().getTime()}`;++ return {+ createTeamName,+ initNewTeam: (baseTeam: Team) => {+ const team = Object.assign({}, baseTeam);+ team.config.config.name = createTeamName();+ return team;+ },+ };+};diff --git a/python/packages/autogen-studio/frontend/src/components/views/team/manager.tsx b/python/packages/autogen-studio/frontend/src/components/views/team/manager.tsxindex dca1fafe6..16d26245c 100644--- a/python/packages/autogen-studio/frontend/src/components/views/team/manager.tsx+++ b/python/packages/autogen-studio/frontend/src/components/views/team/manager.tsx@@ -37,6 +37,7 @@ export const TeamManager: React.FC = () => {setIsLoading(true);const data = await teamAPI.listTeams(user.email);setTeams(data);+ // console.log("team data", data);if (!currentTeam && data.length > 0) {setCurrentTeam(data[0]);}@@ -143,7 +144,7 @@ export const TeamManager: React.FC = () => {updated_at: undefined, // Let server handle timestamps};- console.log("teamData", sanitizedTeamData);+ // console.log("teamData", sanitizedTeamData);const savedTeam = await teamAPI.createTeam(sanitizedTeamData, user.email);messageApi.success(@@ -201,7 +202,7 @@ export const TeamManager: React.FC = () => {<><ChevronRight className="w-4 h-4 text-secondary" /><span className="text-secondary">- {currentTeam.config.name}+ {currentTeam.component?.label}{currentTeam.id ? ("") : (diff --git a/python/packages/autogen-studio/frontend/src/components/views/team/sidebar.tsx b/python/packages/autogen-studio/frontend/src/components/views/team/sidebar.tsxindex 42f6a9c3b..d64917a60 100644--- a/python/packages/autogen-studio/frontend/src/components/views/team/sidebar.tsx+++ b/python/packages/autogen-studio/frontend/src/components/views/team/sidebar.tsx@@ -42,12 +42,12 @@ export const TeamSidebar: React.FC<TeamSidebarProps> = ({isLoading = false,}) => {const defaultGallery = useGalleryStore((state) => state.getDefaultGallery());-const createTeam = () => {const newTeam = Object.assign({}, defaultTeam);- newTeam.config.name = "new_team_" + new Date().getTime();+ newTeam.component.label = "new_team_" + new Date().getTime();onCreateTeam(newTeam);};+// Render collapsed stateif (!isOpen) {return (@@ -161,7 +161,7 @@ export const TeamSidebar: React.FC<TeamSidebarProps> = ({{/* Team Name and Actions Row */}<div className="flex items-center justify-between"><span className="font-medium truncate">- {team.config.name}+ {team.component?.label}</span><div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">{/* <Tooltip title="Edit team">@@ -195,13 +195,13 @@ export const TeamSidebar: React.FC<TeamSidebarProps> = ({{/* Team Metadata Row */}<div className="mt-1 flex items-center gap-2 text-xs text-secondary"><span className="bg-secondary/20 truncate rounded">- {team.config.team_type}+ {team.component.component_type}</span><div className="flex items-center gap-1"><Bot className="w-3 h-3" /><span>- {team.config.participants.length}{" "}- {team.config.participants.length === 1+ {team.component.config.participants.length}{" "}+ {team.component.config.participants.length === 1? "agent": "agents"}</span>@@ -232,7 +232,7 @@ export const TeamSidebar: React.FC<TeamSidebarProps> = ({<div key={"gallery_content"} className="scroll overflow-y-auto">{defaultGallery?.items.teams.map((galleryTeam) => (<div- key={galleryTeam.name + galleryTeam.team_type}+ key={galleryTeam.label + galleryTeam.component_type}className="relative border-secondary"><div@@ -243,7 +243,7 @@ export const TeamSidebar: React.FC<TeamSidebarProps> = ({{/* Team Name and Use Template Action */}<div className="flex items-center justify-between"><span className="font-medium truncate">- {galleryTeam.name}+ {galleryTeam.label}</span><div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity"><Tooltip title="Use as template">@@ -254,10 +254,10 @@ export const TeamSidebar: React.FC<TeamSidebarProps> = ({icon={<Copy className="w-4 h-4" />}onClick={(e) => {e.stopPropagation();- galleryTeam.name =- galleryTeam.name + "_" + new Date().getTime();+ galleryTeam.label =+ galleryTeam.label + "_" + new Date().getTime();onCreateTeam({- config: galleryTeam,+ component: galleryTeam,});}}/>@@ -268,13 +268,13 @@ export const TeamSidebar: React.FC<TeamSidebarProps> = ({{/* Team Metadata Row */}<div className="mt-1 flex items-center gap-2 text-xs text-secondary"><span className="bg-secondary/20 truncate rounded">- {galleryTeam.team_type}+ {galleryTeam.component_type}</span><div className="flex items-center gap-1"><Bot className="w-3 h-3" /><span>- {galleryTeam.participants.length}{" "}- {galleryTeam.participants.length === 1+ {galleryTeam.config.participants.length}{" "}+ {galleryTeam.config.participants.length === 1? "agent": "agents"}</span>diff --git a/python/packages/autogen-studio/frontend/src/components/views/team/types.ts b/python/packages/autogen-studio/frontend/src/components/views/team/types.tsindex fd29035eb..fe4a5fa28 100644--- a/python/packages/autogen-studio/frontend/src/components/views/team/types.ts+++ b/python/packages/autogen-studio/frontend/src/components/views/team/types.ts@@ -1,4 +1,4 @@-import type { Team, TeamConfig } from "../../types/datamodel";+import type { Component, Team, TeamConfig } from "../../types/datamodel";export interface TeamEditorProps {team?: Team;@@ -16,32 +16,92 @@ export interface TeamListProps {isLoading?: boolean;}-export const defaultTeamConfig: TeamConfig = {- version: "1.0.0",+export const defaultTeamConfig: Component<TeamConfig> = {+ provider: "autogen_agentchat.teams.RoundRobinGroupChat",component_type: "team",- name: "default_team",- participants: [- {- component_type: "agent",- name: "assistant_agent",- agent_type: "AssistantAgent",- system_message:- "You are a helpful assistant. Solve tasks carefully. When done respond with TERMINATE",- model_client: {- component_type: "model",- model: "gpt-4o-2024-08-06",- model_type: "OpenAIChatCompletionClient",+ version: 1,+ component_version: 1,+ description:+ "A team of agents that chat with users in a round-robin fashion.",+ label: "General Team",+ config: {+ participants: [+ {+ provider: "autogen_agentchat.agents.AssistantAgent",+ component_type: "agent",+ version: 1,+ component_version: 1,+ config: {+ name: "weather_agent",+ model_client: {+ provider: "autogen_ext.models.openai.OpenAIChatCompletionClient",+ component_type: "model",+ version: 1,+ component_version: 1,+ config: { model: "gpt-4o-mini" },+ },+ tools: [+ {+ provider: "autogen_core.tools.FunctionTool",+ component_type: "tool",+ version: 1,+ component_version: 1,+ config: {+ source_code:+ 'async def get_weather(city: str) -> str:\n return f"The weather in {city} is 73 degrees and Sunny."\n',+ name: "get_weather",+ description: "",+ global_imports: [],+ has_cancellation_support: false,+ },+ },+ ],+ handoffs: [],+ model_context: {+ provider:+ "autogen_core.model_context.UnboundedChatCompletionContext",+ component_type: "chat_completion_context",+ version: 1,+ component_version: 1,+ config: {},+ },+ description:+ "An agent that provides assistance with ability to use tools.",+ system_message:+ "You are a helpful AI assistant. Solve tasks using your tools. Reply with TERMINATE when the task has been completed.",+ reflect_on_tool_use: false,+ tool_call_summary_format: "{result}",+ },+ },+ ],+ termination_condition: {+ provider: "autogen_agentchat.base.OrTerminationCondition",+ component_type: "termination",+ version: 1,+ component_version: 1,+ config: {+ conditions: [+ {+ provider: "autogen_agentchat.conditions.MaxMessageTermination",+ component_type: "termination",+ version: 1,+ component_version: 1,+ config: { max_messages: 10 },+ },+ {+ provider: "autogen_agentchat.conditions.TextMentionTermination",+ component_type: "termination",+ version: 1,+ component_version: 1,+ config: { text: "TERMINATE" },+ },+ ],},},- ],- team_type: "RoundRobinGroupChat",- termination_condition: {- component_type: "termination",- termination_type: "MaxMessageTermination",- max_messages: 3,+ max_turns: 1,},};export const defaultTeam: Team = {- config: defaultTeamConfig,+ component: defaultTeamConfig,};diff --git a/python/packages/autogen-studio/tests/test_component_factory.py b/python/packages/autogen-studio/tests/test_component_factory.pydeleted file mode 100644index c5339cc70..000000000--- a/python/packages/autogen-studio/tests/test_component_factory.py+++ /dev/null@@ -1,397 +0,0 @@-import pytest-from typing import List--from autogen_agentchat.agents import AssistantAgent-from autogen_agentchat.teams import RoundRobinGroupChat, SelectorGroupChat, MagenticOneGroupChat-from autogen_agentchat.conditions import MaxMessageTermination, StopMessageTermination, TextMentionTermination-from autogen_core.tools import FunctionTool--from autogenstudio.datamodel.types import (- AssistantAgentConfig,- OpenAIModelConfig,- RoundRobinTeamConfig,- SelectorTeamConfig,- MagenticOneTeamConfig,- ToolConfig,- MaxMessageTerminationConfig,- StopMessageTerminationConfig,- TextMentionTerminationConfig,- CombinationTerminationConfig,- ModelTypes,- AgentTypes,- TeamTypes,- TerminationTypes,- ToolTypes,- ComponentTypes,-)-from autogenstudio.database import ComponentFactory---def component_factory():- return ComponentFactory()---def sample_tool_config():- return ToolConfig(- name="calculator",- description="A simple calculator function",- content="""-def calculator(a: int, b: int, operation: str = '+') -> int:- '''- A simple calculator that performs basic operations- '''- if operation == '+':- return a + b- elif operation == '-':- return a - b- elif operation == '*':- return a * b- elif operation == '/':- return a / b- else:- raise ValueError("Invalid operation")-""",- tool_type=ToolTypes.PYTHON_FUNCTION,- component_type=ComponentTypes.TOOL,- version="1.0.0",- )---def sample_model_config():- return OpenAIModelConfig(- model_type=ModelTypes.OPENAI,- model="gpt-4",- api_key="test-key",- component_type=ComponentTypes.MODEL,- version="1.0.0",- )---def sample_agent_config(sample_model_config: OpenAIModelConfig, sample_tool_config: ToolConfig):- return AssistantAgentConfig(- name="test_agent",- agent_type=AgentTypes.ASSISTANT,- system_message="You are a helpful assistant",- model_client=sample_model_config,- tools=[sample_tool_config],- component_type=ComponentTypes.AGENT,- version="1.0.0",- )---def sample_termination_config():- return MaxMessageTerminationConfig(- termination_type=TerminationTypes.MAX_MESSAGES,- max_messages=10,- component_type=ComponentTypes.TERMINATION,- version="1.0.0",- )---def sample_team_config(- sample_agent_config: AssistantAgentConfig, sample_termination_config: MaxMessageTerminationConfig, sample_model_config: OpenAIModelConfig-):- return RoundRobinTeamConfig(- name="test_team",- team_type=TeamTypes.ROUND_ROBIN,- participants=[sample_agent_config],- termination_condition=sample_termination_config,- model_client=sample_model_config,- component_type=ComponentTypes.TEAM,- max_turns=10,- version="1.0.0",- )---async def test_load_tool(component_factory: ComponentFactory, sample_tool_config: ToolConfig):- # Test loading tool from ToolConfig- tool = await component_factory.load_tool(sample_tool_config)- assert isinstance(tool, FunctionTool)- assert tool.name == "calculator"- assert tool.description == "A simple calculator function"-- # Test tool functionality- result = tool._func(5, 3, "+")- assert result == 8---async def test_load_tool_invalid_config(component_factory: ComponentFactory):- # Test with missing required fields- with pytest.raises(ValueError):- await component_factory.load_tool(- ToolConfig(- name="test",- description="",- content="",- tool_type=ToolTypes.PYTHON_FUNCTION,- component_type=ComponentTypes.TOOL,- version="1.0.0",- )- )-- # Test with invalid Python code- invalid_config = ToolConfig(- name="invalid",- description="Invalid function",- content="def invalid_func(): return invalid syntax",- tool_type=ToolTypes.PYTHON_FUNCTION,- component_type=ComponentTypes.TOOL,- version="1.0.0",- )- with pytest.raises(ValueError):- await component_factory.load_tool(invalid_config)---async def test_load_model(component_factory: ComponentFactory, sample_model_config: OpenAIModelConfig):- # Test loading model from ModelConfig- model = await component_factory.load_model(sample_model_config)- assert model is not None---async def test_load_agent(component_factory: ComponentFactory, sample_agent_config: AssistantAgentConfig):- # Test loading agent from AgentConfig- agent = await component_factory.load_agent(sample_agent_config)- assert isinstance(agent, AssistantAgent)- assert agent.name == "test_agent"- assert len(agent._tools) == 1---async def test_load_termination(component_factory: ComponentFactory):-- max_msg_config = MaxMessageTerminationConfig(- termination_type=TerminationTypes.MAX_MESSAGES,- max_messages=5,- component_type=ComponentTypes.TERMINATION,- version="1.0.0",- )- termination = await component_factory.load_termination(max_msg_config)- assert isinstance(termination, MaxMessageTermination)- assert termination._max_messages == 5-- # Test StopMessageTermination- stop_msg_config = StopMessageTerminationConfig(- termination_type=TerminationTypes.STOP_MESSAGE, component_type=ComponentTypes.TERMINATION, version="1.0.0"- )- termination = await component_factory.load_termination(stop_msg_config)- assert isinstance(termination, StopMessageTermination)-- # Test TextMentionTermination- text_mention_config = TextMentionTerminationConfig(- termination_type=TerminationTypes.TEXT_MENTION,- text="DONE",- component_type=ComponentTypes.TERMINATION,- version="1.0.0",- )- termination = await component_factory.load_termination(text_mention_config)- assert isinstance(termination, TextMentionTermination)- assert termination._text == "DONE"-- # Test AND combination- and_combo_config = CombinationTerminationConfig(- termination_type=TerminationTypes.COMBINATION,- operator="and",- conditions=[- MaxMessageTerminationConfig(- termination_type=TerminationTypes.MAX_MESSAGES,- max_messages=5,- component_type=ComponentTypes.TERMINATION,- version="1.0.0",- ),- TextMentionTerminationConfig(- termination_type=TerminationTypes.TEXT_MENTION,- text="DONE",- component_type=ComponentTypes.TERMINATION,- version="1.0.0",- ),- ],- component_type=ComponentTypes.TERMINATION,- version="1.0.0",- )- termination = await component_factory.load_termination(and_combo_config)- assert termination is not None-- # Test OR combination- or_combo_config = CombinationTerminationConfig(- termination_type=TerminationTypes.COMBINATION,- operator="or",- conditions=[- MaxMessageTerminationConfig(- termination_type=TerminationTypes.MAX_MESSAGES,- max_messages=5,- component_type=ComponentTypes.TERMINATION,- version="1.0.0",- ),- TextMentionTerminationConfig(- termination_type=TerminationTypes.TEXT_MENTION,- text="DONE",- component_type=ComponentTypes.TERMINATION,- version="1.0.0",- ),- ],- component_type=ComponentTypes.TERMINATION,- version="1.0.0",- )- termination = await component_factory.load_termination(or_combo_config)- assert termination is not None-- # Test invalid combinations- with pytest.raises(ValueError):- await component_factory.load_termination(- CombinationTerminationConfig(- termination_type=TerminationTypes.COMBINATION,- conditions=[], # Empty conditions- component_type=ComponentTypes.TERMINATION,- version="1.0.0",- )- )-- with pytest.raises(ValueError):- await component_factory.load_termination(- CombinationTerminationConfig(- termination_type=TerminationTypes.COMBINATION,- operator="invalid", # type: ignore- conditions=[- MaxMessageTerminationConfig(- termination_type=TerminationTypes.MAX_MESSAGES,- max_messages=5,- component_type=ComponentTypes.TERMINATION,- version="1.0.0",- )- ],- component_type=ComponentTypes.TERMINATION,- version="1.0.0",- )- )-- # Test missing operator- with pytest.raises(ValueError):- await component_factory.load_termination(- CombinationTerminationConfig(- termination_type=TerminationTypes.COMBINATION,- conditions=[- MaxMessageTerminationConfig(- termination_type=TerminationTypes.MAX_MESSAGES,- max_messages=5,- component_type=ComponentTypes.TERMINATION,- version="1.0.0",- ),- TextMentionTerminationConfig(- termination_type=TerminationTypes.TEXT_MENTION,- text="DONE",- component_type=ComponentTypes.TERMINATION,- version="1.0.0",- ),- ],- component_type=ComponentTypes.TERMINATION,- version="1.0.0",- )- )---async def test_load_team(- component_factory: ComponentFactory, sample_team_config: RoundRobinTeamConfig, sample_model_config: OpenAIModelConfig-):- # Test loading RoundRobinGroupChat team- team = await component_factory.load_team(sample_team_config)- assert isinstance(team, RoundRobinGroupChat)- assert len(team._participants) == 1-- # Test loading SelectorGroupChat team with multiple participants- selector_team_config = SelectorTeamConfig(- name="selector_team",- team_type=TeamTypes.SELECTOR,- participants=[ # Add two participants- sample_team_config.participants[0], # First agent- AssistantAgentConfig( # Second agent- name="test_agent_2",- agent_type=AgentTypes.ASSISTANT,- system_message="You are another helpful assistant",- model_client=sample_model_config,- tools=sample_team_config.participants[0].tools,- component_type=ComponentTypes.AGENT,- version="1.0.0",- ),- ],- termination_condition=sample_team_config.termination_condition,- model_client=sample_model_config,- component_type=ComponentTypes.TEAM,- version="1.0.0",- )- team = await component_factory.load_team(selector_team_config)- assert isinstance(team, SelectorGroupChat)- assert len(team._participants) == 2-- # Test loading MagenticOneGroupChat team- magentic_one_config = MagenticOneTeamConfig(- name="magentic_one_team",- team_type=TeamTypes.MAGENTIC_ONE,- participants=[ # Add two participants- sample_team_config.participants[0], # First agent- AssistantAgentConfig( # Second agent- name="test_agent_2",- agent_type=AgentTypes.ASSISTANT,- system_message="You are another helpful assistant",- model_client=sample_model_config,- tools=sample_team_config.participants[0].tools,- component_type=ComponentTypes.AGENT,- max_turns=sample_team_config.max_turns,- version="1.0.0",- ),- ],- termination_condition=sample_team_config.termination_condition,- model_client=sample_model_config,- component_type=ComponentTypes.TEAM,- version="1.0.0",- )- team = await component_factory.load_team(magentic_one_config)- assert isinstance(team, MagenticOneGroupChat)- assert len(team._participants) == 2---async def test_invalid_configs(component_factory: ComponentFactory):- # Test invalid agent type- with pytest.raises(ValueError):- await component_factory.load_agent(- AssistantAgentConfig(- name="test",- agent_type="InvalidAgent", # type: ignore- system_message="test",- component_type=ComponentTypes.AGENT,- version="1.0.0",- )- )-- # Test invalid team type- with pytest.raises(ValueError):- await component_factory.load_team(- RoundRobinTeamConfig(- name="test",- team_type="InvalidTeam", # type: ignore- participants=[],- component_type=ComponentTypes.TEAM,- version="1.0.0",- )- )-- # Test invalid termination type- with pytest.raises(ValueError):- await component_factory.load_termination(- MaxMessageTerminationConfig(- termination_type="InvalidTermination", # type: ignore- component_type=ComponentTypes.TERMINATION,- version="1.0.0",- )- )diff --git a/python/packages/autogen-studio/tests/test_db_manager.py b/python/packages/autogen-studio/tests/test_db_manager.pyindex a72dfc484..e0fc223a9 100644--- a/python/packages/autogen-studio/tests/test_db_manager.py+++ b/python/packages/autogen-studio/tests/test_db_manager.py@@ -5,16 +5,11 @@ from sqlmodel import Session, text, selectfrom typing import Generatorfrom autogenstudio.database import DatabaseManager-from autogenstudio.datamodel.types import (- ToolConfig,- OpenAIModelConfig,- RoundRobinTeamConfig,- StopMessageTerminationConfig,- AssistantAgentConfig,- ModelTypes, AgentTypes, TeamTypes, ComponentTypes,- TerminationTypes, ToolTypes-)-from autogenstudio.datamodel.db import Model, Tool, Agent, Team, LinkTypes+from autogen_agentchat.agents import AssistantAgent+from autogen_agentchat.teams import RoundRobinGroupChat+from autogen_ext.models.openai import OpenAIChatCompletionClient+from autogen_agentchat.conditions import TextMentionTermination+from autogenstudio.datamodel.db import Team@pytest.fixture@@ -42,69 +37,21 @@ def test_user() -> str:@pytest.fixture-def sample_model(test_user: str) -> Model:- """Create a sample model with proper config"""- return Model(- user_id=test_user,- config=OpenAIModelConfig(+def sample_team(test_user: str) -> Team:+ """Create a sample team with proper config"""+ agent = AssistantAgent(+ name="weather_agent",+ model_client=OpenAIChatCompletionClient(model="gpt-4",- model_type=ModelTypes.OPENAI,- component_type=ComponentTypes.MODEL,- version="1.0.0"- ).model_dump()- )---def sample_tool(test_user: str) -> Tool:- """Create a sample tool with proper config"""- return Tool(- user_id=test_user,- config=ToolConfig(- name="test_tool",- description="A test tool",- content="async def test_func(x: str) -> str:\n return f'Test {x}'",- tool_type=ToolTypes.PYTHON_FUNCTION,- component_type=ComponentTypes.TOOL,- version="1.0.0"- ).model_dump()+ ),)+ agent_team = RoundRobinGroupChat([agent], termination_condition=TextMentionTermination("TERMINATE"))+ team_component = agent_team.dump_component()-def sample_agent(test_user: str, sample_model: Model, sample_tool: Tool) -> Agent:- """Create a sample agent with proper config and relationships"""- return Agent(- user_id=test_user,- config=AssistantAgentConfig(- name="test_agent",- agent_type=AgentTypes.ASSISTANT,- model_client=OpenAIModelConfig.model_validate(sample_model.config),- tools=[ToolConfig.model_validate(sample_tool.config)],- component_type=ComponentTypes.AGENT,- version="1.0.0"- ).model_dump()- )---def sample_team(test_user: str, sample_agent: Agent) -> Team:- """Create a sample team with proper config"""return Team(user_id=test_user,- config=RoundRobinTeamConfig(- name="test_team",- participants=[AssistantAgentConfig.model_validate(- sample_agent.config)],- termination_condition=StopMessageTerminationConfig(- termination_type=TerminationTypes.STOP_MESSAGE,- component_type=ComponentTypes.TERMINATION,- version="1.0.0"- ).model_dump(),- team_type=TeamTypes.ROUND_ROBIN,- component_type=ComponentTypes.TEAM,- version="1.0.0"- ).model_dump()+ component=team_component.model_dump(),)@@ -117,113 +64,52 @@ class TestDatabaseOperations:result = session.exec(select(1)).first()assert result == 1- def test_basic_entity_creation(self, test_db: DatabaseManager, sample_model: Model,- sample_tool: Tool, sample_agent: Agent, sample_team: Team):+ def test_basic_entity_creation(self, test_db: DatabaseManager, sample_team: Team):"""Test creating all entity types with proper configs"""+ # Use upsert instead of raw session+ response = test_db.upsert(sample_team)+ assert response.status is True+with Session(test_db.engine) as session:- # Add all entities- session.add(sample_model)- session.add(sample_tool)- session.add(sample_agent)- session.add(sample_team)- session.commit()-- # Store IDs- model_id = sample_model.id- tool_id = sample_tool.id- agent_id = sample_agent.id- team_id = sample_team.id-- # Verify all entities were created with new session- with Session(test_db.engine) as session:- assert session.get(Model, model_id) is not None- assert session.get(Tool, tool_id) is not None- assert session.get(Agent, agent_id) is not None- assert session.get(Team, team_id) is not None+ saved_team = session.get(Team, sample_team.id)+ assert saved_team is not None- def test_multiple_links(self, test_db: DatabaseManager, sample_agent: Agent):- """Test linking multiple models to an agent"""- with Session(test_db.engine) as session:- # Create two models with updated configs- model1 = Model(- user_id="test_user",- config=OpenAIModelConfig(- model="gpt-4",- model_type=ModelTypes.OPENAI,- component_type=ComponentTypes.MODEL,- version="1.0.0"- ).model_dump()- )- model2 = Model(- user_id="test_user",- config=OpenAIModelConfig(- model="gpt-3.5",- model_type=ModelTypes.OPENAI,- component_type=ComponentTypes.MODEL,- version="1.0.0"- ).model_dump()- )-- # Add and commit all entities- session.add(model1)- session.add(model2)- session.add(sample_agent)- session.commit()-- model1_id = model1.id- model2_id = model2.id- agent_id = sample_agent.id-- # Create links using IDs- test_db.link(LinkTypes.AGENT_MODEL, agent_id, model1_id)- test_db.link(LinkTypes.AGENT_MODEL, agent_id, model2_id)-- # Verify links- linked_models = test_db.get_linked_entities(- LinkTypes.AGENT_MODEL, agent_id)- assert len(linked_models.data) == 2-- # Verify model names- model_names = [model.config["model"] for model in linked_models.data]- assert "gpt-4" in model_names- assert "gpt-3.5" in model_names-- def test_upsert_operations(self, test_db: DatabaseManager, sample_model: Model):+ def test_upsert_operations(self, test_db: DatabaseManager, sample_team: Team):"""Test upsert for both create and update scenarios"""# Test Create- response = test_db.upsert(sample_model)+ response = test_db.upsert(sample_team)assert response.status is Trueassert "Created Successfully" in response.message# Test Update- sample_model.config["model"] = "gpt-4-turbo"- response = test_db.upsert(sample_model)+ team_id = sample_team.id+ sample_team.version = "0.0.2"+ response = test_db.upsert(sample_team)assert response.status is True- assert "Updated Successfully" in response.message# Verify Update- result = test_db.get(Model, {"id": sample_model.id})+ result = test_db.get(Team, {"id": team_id})assert result.status is True- assert result.data[0].config["model"] == "gpt-4-turbo"+ assert result.data[0].version == "0.0.2"- def test_delete_operations(self, test_db: DatabaseManager, sample_model: Model):+ def test_delete_operations(self, test_db: DatabaseManager, sample_team: Team):"""Test delete with various filters"""# First insert the model- test_db.upsert(sample_model)-+ response = test_db.upsert(sample_team)+ assert response.status is True # Verify insert worked++ # Get the ID that was actually saved+ team_id = sample_team.id+# Test deletion by id- response = test_db.delete(Model, {"id": sample_model.id})+ response = test_db.delete(Team, {"id": team_id})assert response.status is Trueassert "Deleted Successfully" in response.message# Verify deletion- result = test_db.get(Model, {"id": sample_model.id})+ result = test_db.get(Team, {"id": team_id})assert len(result.data) == 0- # Test deletion with non-existent id- response = test_db.delete(Model, {"id": 999999})- assert "Row not found" in response.message-def test_initialize_database_scenarios(self):"""Test different initialize_database parameters"""db_path = "test_init.db"@@ -242,4 +128,4 @@ class TestDatabaseOperations:asyncio.run(db.close())db.reset_db()if os.path.exists(db_path):- os.remove(db_path)+ os.remove(db_path)\ No newline at end of file