A programming framework for agentic AI
Improve Gallery Editor UX in AGS (#5613)
Victor Dibia2f4300562471
diff --git a/python/packages/autogen-studio/autogenstudio/datamodel/__init__.py b/python/packages/autogen-studio/autogenstudio/datamodel/__init__.pyindex b7f6f8da5..435031aab 100644--- a/python/packages/autogen-studio/autogenstudio/datamodel/__init__.py+++ b/python/packages/autogen-studio/autogenstudio/datamodel/__init__.py@@ -2,7 +2,6 @@ from .db import Message, Run, RunStatus, Session, Teamfrom .types import (Gallery,GalleryComponents,- GalleryItems,GalleryMetadata,LLMCallEventMessage,MessageConfig,@@ -24,4 +23,7 @@ __all__ = ["Response","SocketMessage","LLMCallEventMessage",+ "Gallery",+ "GalleryComponents",+ "GalleryMetadata",]diff --git a/python/packages/autogen-studio/autogenstudio/datamodel/types.py b/python/packages/autogen-studio/autogenstudio/datamodel/types.pyindex 3e3bdbbe4..8475a891e 100644--- a/python/packages/autogen-studio/autogenstudio/datamodel/types.py+++ b/python/packages/autogen-studio/autogenstudio/datamodel/types.py@@ -52,11 +52,7 @@ class GalleryComponents(BaseModel):models: List[ComponentModel]tools: List[ComponentModel]terminations: List[ComponentModel]---class GalleryItems(BaseModel):teams: List[ComponentModel]- components: GalleryComponentsclass Gallery(BaseModel):@@ -64,7 +60,7 @@ class Gallery(BaseModel):name: strurl: Optional[str] = Nonemetadata: GalleryMetadata- items: GalleryItems+ components: GalleryComponents# web request/response data modelsdiff --git a/python/packages/autogen-studio/autogenstudio/gallery/builder.py b/python/packages/autogen-studio/autogenstudio/gallery/builder.pyindex 9c2b8c9d0..78ba42ca3 100644--- a/python/packages/autogen-studio/autogenstudio/gallery/builder.py+++ b/python/packages/autogen-studio/autogenstudio/gallery/builder.py@@ -10,7 +10,7 @@ from autogen_ext.agents.web_surfer import MultimodalWebSurferfrom autogen_ext.models.openai import OpenAIChatCompletionClientfrom autogen_ext.models.openai._openai_client import AzureOpenAIChatCompletionClient-from autogenstudio.datamodel import Gallery, GalleryComponents, GalleryItems, GalleryMetadata+from autogenstudio.datamodel import Gallery, GalleryComponents, GalleryMetadatafrom . import tools as tools@@ -119,11 +119,12 @@ class GalleryBuilder:name=self.name,url=self.url,metadata=self.metadata,- items=GalleryItems(+ components=GalleryComponents(teams=self.teams,- components=GalleryComponents(- agents=self.agents, models=self.models, tools=self.tools, terminations=self.terminations- ),+ agents=self.agents,+ models=self.models,+ tools=self.tools,+ terminations=self.terminations,),)@@ -195,7 +196,11 @@ def create_default_gallery() -> Gallery:builder.add_termination(calc_text_term.dump_component())builder.add_termination(calc_max_term.dump_component())- builder.add_termination(calc_or_term.dump_component())+ builder.add_termination(+ calc_or_term.dump_component(),+ label="OR Termination",+ description="Termination condition that ends the conversation when either a message contains 'TERMINATE' or the maximum number of messages is reached.",+ )# Create calculator teamcalc_team = RoundRobinGroupChat(participants=[calc_assistant], termination_condition=calc_or_term)@@ -227,7 +232,11 @@ def create_default_gallery() -> Gallery:model_client=base_model,headless=True,)- builder.add_agent(websurfer_agent.dump_component())+ builder.add_agent(+ websurfer_agent.dump_component(),+ label="Web Surfer Agent",+ description="An agent that solves tasks by browsing the web using a headless browser.",+ )# Create verification assistantverification_assistant = AssistantAgent(@@ -236,7 +245,11 @@ def create_default_gallery() -> Gallery: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=base_model,)- builder.add_agent(verification_assistant.dump_component())+ builder.add_agent(+ verification_assistant.dump_component(),+ label="Verification Assistant",+ description="an agent that verifies and summarizes information",+ )# Create user proxyweb_user_proxy = UserProxyAgent(diff --git a/python/packages/autogen-studio/frontend/src/components/sidebar.tsx b/python/packages/autogen-studio/frontend/src/components/sidebar.tsxindex 0b4bd3c38..8b060771e 100644--- a/python/packages/autogen-studio/frontend/src/components/sidebar.tsx+++ b/python/packages/autogen-studio/frontend/src/components/sidebar.tsx@@ -105,7 +105,7 @@ const Sidebar = ({ link, meta, isMobile }: SidebarProps) => {return (<divclassName={classNames(- "flex grow flex-col gap-y-5 overflow-y-auto border-r border-secondary bg-primary",+ "flex grow border z-50 flex-col gap-y-5 overflow-y-auto border-r border-secondary bg-primary","transition-all duration-300 ease-in-out",showFull ? "w-72 px-6" : "w-16 px-2")}diff --git a/python/packages/autogen-studio/frontend/src/components/views/atoms.tsx b/python/packages/autogen-studio/frontend/src/components/views/atoms.tsxindex ba98d17ee..eea5d5f23 100644--- a/python/packages/autogen-studio/frontend/src/components/views/atoms.tsx+++ b/python/packages/autogen-studio/frontend/src/components/views/atoms.tsx@@ -57,6 +57,13 @@ export const LoadingDots = ({ size = 8 }) => {// import { Minimize2, Maximize2, ArrowsMaximize, X } from 'lucide-react';// import { Tooltip } from 'antd';+function safeJsonStringify(input: any): string {+ if (typeof input === "object" && input !== null) {+ return JSON.stringify(input);+ }+ return input;+}+export const TruncatableText = memo(({content = "",@@ -76,10 +83,12 @@ export const TruncatableText = memo(const [isExpanded, setIsExpanded] = useState(false);const [isFullscreen, setIsFullscreen] = useState(false);const threshold = isJson ? jsonThreshold : textThreshold;+ content = safeJsonStringify(content) + "";const shouldTruncate = content.length > threshold;- const toggleExpand = () => {+ const toggleExpand = (e: React.MouseEvent) => {setIsExpanded(!isExpanded);+ e.stopPropagation();};const displayContent =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.jsonindex ac2a1dbbe..8494cc0a9 100644--- 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.json@@ -4,8 +4,8 @@"url": null,"metadata": {"author": "AutoGen Team",- "created_at": "2025-02-11T18:37:53.922275",- "updated_at": "2025-02-11T18:37:54.268540",+ "created_at": "2025-02-18T16:52:37.999327",+ "updated_at": "2025-02-18T16:52:38.055078","version": "1.0.0","description": "A default gallery containing basic components for human-in-loop conversations","tags": ["human-in-loop", "assistant", "web agents"],@@ -14,7 +14,437 @@"category": "conversation","last_synced": null},- "items": {+ "components": {+ "agents": [+ {+ "provider": "autogen_agentchat.agents.AssistantAgent",+ "component_type": "agent",+ "version": 1,+ "component_version": 1,+ "description": "An agent that provides assistance with ability to use tools.",+ "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": "OpenAI GPT-4o-mini",+ "label": "OpenAI GPT-4o Mini",+ "config": {+ "model": "gpt-4o-mini"+ }+ },+ {+ "provider": "autogen_ext.models.openai.OpenAIChatCompletionClient",+ "component_type": "model",+ "version": 1,+ "component_version": 1,+ "description": "Local Mistral-7B model client for instruction-based generation (Ollama, LMStudio).",+ "label": "Mistral-7B Local",+ "config": {+ "model": "TheBloke/Mistral-7B-Instruct-v0.2-GGUF",+ "model_info": {+ "vision": false,+ "function_calling": true,+ "json_output": false,+ "family": "unknown"+ },+ "base_url": "http://localhost:1234/v1"+ }+ },+ {+ "provider": "autogen_ext.models.openai.AzureOpenAIChatCompletionClient",+ "component_type": "model",+ "version": 1,+ "component_version": 1,+ "description": "GPT-4o Mini Azure OpenAI model client.",+ "label": "AzureOpenAI GPT-4o-mini",+ "config": {+ "model": "gpt-4o-mini",+ "api_key": "sk-...",+ "azure_endpoint": "https://{your-custom-endpoint}.openai.azure.com/",+ "azure_deployment": "{your-azure-deployment}",+ "api_version": "2024-06-01"+ }+ }+ ],+ "tools": [+ {+ "provider": "autogen_core.tools.FunctionTool",+ "component_type": "tool",+ "version": 1,+ "component_version": 1,+ "description": "A tool that performs basic arithmetic operations (addition, subtraction, multiplication, division).",+ "label": "Calculator Tool",+ "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+ }+ },+ {+ "provider": "autogen_core.tools.FunctionTool",+ "component_type": "tool",+ "version": 1,+ "component_version": 1,+ "description": "A tool that generates images based on a text description using OpenAI's DALL-E model. Note: Requires OpenAI API key to function.",+ "label": "Image Generation Tool",+ "config": {+ "source_code": "async def generate_image(\n query: str, output_dir: Optional[Path] = None, image_size: Literal[\"1024x1024\", \"512x512\", \"256x256\"] = \"1024x1024\"\n) -> List[str]:\n \"\"\"\n Generate images using OpenAI's DALL-E model based on a text description.\n\n Args:\n query: Natural language description of the desired image\n output_dir: Directory to save generated images (default: current directory)\n image_size: Size of generated image (1024x1024, 512x512, or 256x256)\n\n Returns:\n List[str]: Paths to the generated image files\n \"\"\"\n # Initialize the OpenAI client\n client = OpenAI()\n\n # Generate images using DALL-E 3\n response = client.images.generate(model=\"dall-e-3\", prompt=query, n=1, response_format=\"b64_json\", size=image_size)\n\n saved_files = []\n\n # Process the response\n if response.data:\n for image_data in response.data:\n # Generate a unique filename\n file_name = f\"{uuid.uuid4()}.png\"\n\n # Use output_dir if provided, otherwise use current directory\n file_path = Path(output_dir) / file_name if output_dir else Path(file_name)\n\n base64_str = image_data.b64_json\n img = Image.open(io.BytesIO(base64.decodebytes(bytes(base64_str, \"utf-8\"))))\n\n # Save the image to a file\n img.save(file_path)\n\n saved_files.append(str(file_path))\n\n return saved_files\n",+ "name": "generate_image",+ "description": "Generate images using DALL-E based on text descriptions.",+ "global_imports": [+ "io",+ "uuid",+ "base64",+ {+ "module": "typing",+ "imports": ["List", "Optional", "Literal"]+ },+ {+ "module": "pathlib",+ "imports": ["Path"]+ },+ {+ "module": "openai",+ "imports": ["OpenAI"]+ },+ {+ "module": "PIL",+ "imports": ["Image"]+ }+ ],+ "has_cancellation_support": false+ }+ },+ {+ "provider": "autogen_core.tools.FunctionTool",+ "component_type": "tool",+ "version": 1,+ "component_version": 1,+ "description": "A tool that generates a PDF file from a list of images.Requires the PyFPDF and pillow library to function.",+ "label": "PDF Generation Tool",+ "config": {+ "source_code": "async def generate_pdf(\n sections: List[Dict[str, Optional[str]]], output_file: str = \"report.pdf\", report_title: str = \"PDF Report\"\n) -> str:\n \"\"\"\n Generate a PDF report with formatted sections including text and images.\n\n Args:\n sections: List of dictionaries containing section details with keys:\n - title: Section title\n - level: Heading level (title, h1, h2)\n - content: Section text content\n - image: Optional image URL or file path\n output_file: Name of output PDF file\n report_title: Title shown at top of report\n\n Returns:\n str: Path to the generated PDF file\n \"\"\"\n\n def normalize_text(text: str) -> str:\n \"\"\"Normalize Unicode text to ASCII.\"\"\"\n return unicodedata.normalize(\"NFKD\", text).encode(\"ascii\", \"ignore\").decode(\"ascii\")\n\n def get_image(image_url_or_path):\n \"\"\"Fetch image from URL or local path.\"\"\"\n if image_url_or_path.startswith((\"http://\", \"https://\")):\n response = requests.get(image_url_or_path)\n if response.status_code == 200:\n return BytesIO(response.content)\n elif Path(image_url_or_path).is_file():\n return open(image_url_or_path, \"rb\")\n return None\n\n def add_rounded_corners(img, radius=6):\n \"\"\"Add rounded corners to an image.\"\"\"\n mask = Image.new(\"L\", img.size, 0)\n draw = ImageDraw.Draw(mask)\n draw.rounded_rectangle([(0, 0), img.size], radius, fill=255)\n img = ImageOps.fit(img, mask.size, centering=(0.5, 0.5))\n img.putalpha(mask)\n return img\n\n class PDF(FPDF):\n \"\"\"Custom PDF class with header and content formatting.\"\"\"\n\n def header(self):\n self.set_font(\"Arial\", \"B\", 12)\n normalized_title = normalize_text(report_title)\n self.cell(0, 10, normalized_title, 0, 1, \"C\")\n\n def chapter_title(self, txt):\n self.set_font(\"Arial\", \"B\", 12)\n normalized_txt = normalize_text(txt)\n self.cell(0, 10, normalized_txt, 0, 1, \"L\")\n self.ln(2)\n\n def chapter_body(self, body):\n self.set_font(\"Arial\", \"\", 12)\n normalized_body = normalize_text(body)\n self.multi_cell(0, 10, normalized_body)\n self.ln()\n\n def add_image(self, img_data):\n img = Image.open(img_data)\n img = add_rounded_corners(img)\n img_path = Path(f\"temp_{uuid.uuid4().hex}.png\")\n img.save(img_path, format=\"PNG\")\n self.image(str(img_path), x=None, y=None, w=190 if img.width > 190 else img.width)\n self.ln(10)\n img_path.unlink()\n\n # Initialize PDF\n pdf = PDF()\n pdf.add_page()\n font_size = {\"title\": 16, \"h1\": 14, \"h2\": 12, \"body\": 12}\n\n # Add sections\n for section in sections:\n title = section.get(\"title\", \"\")\n level = section.get(\"level\", \"h1\")\n content = section.get(\"content\", \"\")\n image = section.get(\"image\")\n\n pdf.set_font(\"Arial\", \"B\" if level in font_size else \"\", font_size.get(level, font_size[\"body\"]))\n pdf.chapter_title(title)\n\n if content:\n pdf.chapter_body(content)\n\n if image:\n img_data = get_image(image)\n if img_data:\n pdf.add_image(img_data)\n if isinstance(img_data, BytesIO):\n img_data.close()\n\n pdf.output(output_file)\n return output_file\n",+ "name": "generate_pdf",+ "description": "Generate PDF reports with formatted sections containing text and images",+ "global_imports": [+ "uuid",+ "requests",+ "unicodedata",+ {+ "module": "typing",+ "imports": ["List", "Dict", "Optional"]+ },+ {+ "module": "pathlib",+ "imports": ["Path"]+ },+ {+ "module": "fpdf",+ "imports": ["FPDF"]+ },+ {+ "module": "PIL",+ "imports": ["Image", "ImageDraw", "ImageOps"]+ },+ {+ "module": "io",+ "imports": ["BytesIO"]+ }+ ],+ "has_cancellation_support": false+ }+ },+ {+ "provider": "autogen_core.tools.FunctionTool",+ "component_type": "tool",+ "version": 1,+ "component_version": 1,+ "description": "A tool that fetches the content of a webpage and converts it to markdown. Requires the requests and beautifulsoup4 library to function.",+ "label": "Fetch Webpage Tool",+ "config": {+ "source_code": "async def fetch_webpage(\n url: str, include_images: bool = True, max_length: Optional[int] = None, headers: Optional[Dict[str, str]] = None\n) -> str:\n \"\"\"Fetch a webpage and convert it to markdown format.\n\n Args:\n url: The URL of the webpage to fetch\n include_images: Whether to include image references in the markdown\n max_length: Maximum length of the output markdown (if None, no limit)\n headers: Optional HTTP headers for the request\n\n Returns:\n str: Markdown version of the webpage content\n\n Raises:\n ValueError: If the URL is invalid or the page can't be fetched\n \"\"\"\n # Use default headers if none provided\n if headers is None:\n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\"}\n\n try:\n # Fetch the webpage\n async with httpx.AsyncClient() as client:\n response = await client.get(url, headers=headers, timeout=10)\n response.raise_for_status()\n\n # Parse HTML\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n # Remove script and style elements\n for script in soup([\"script\", \"style\"]):\n script.decompose()\n\n # Convert relative URLs to absolute\n for tag in soup.find_all([\"a\", \"img\"]):\n if tag.get(\"href\"):\n tag[\"href\"] = urljoin(url, tag[\"href\"])\n if tag.get(\"src\"):\n tag[\"src\"] = urljoin(url, tag[\"src\"])\n\n # Configure HTML to Markdown converter\n h2t = html2text.HTML2Text()\n h2t.body_width = 0 # No line wrapping\n h2t.ignore_images = not include_images\n h2t.ignore_emphasis = False\n h2t.ignore_links = False\n h2t.ignore_tables = False\n\n # Convert to markdown\n markdown = h2t.handle(str(soup))\n\n # Trim if max_length is specified\n if max_length and len(markdown) > max_length:\n markdown = markdown[:max_length] + \"\\n...(truncated)\"\n\n return markdown.strip()\n\n except httpx.RequestError as e:\n raise ValueError(f\"Failed to fetch webpage: {str(e)}\") from e\n except Exception as e:\n raise ValueError(f\"Error processing webpage: {str(e)}\") from e\n",+ "name": "fetch_webpage",+ "description": "Fetch a webpage and convert it to markdown format, with options for including images and limiting length",+ "global_imports": [+ "os",+ "html2text",+ {+ "module": "typing",+ "imports": ["Optional", "Dict"]+ },+ "httpx",+ {+ "module": "bs4",+ "imports": ["BeautifulSoup"]+ },+ {+ "module": "html2text",+ "imports": ["HTML2Text"]+ },+ {+ "module": "urllib.parse",+ "imports": ["urljoin"]+ }+ ],+ "has_cancellation_support": false+ }+ },+ {+ "provider": "autogen_core.tools.FunctionTool",+ "component_type": "tool",+ "version": 1,+ "component_version": 1,+ "description": "A tool that performs Bing searches using the Bing Web Search API. Requires the requests library, BING_SEARCH_KEY env variable to function.",+ "label": "Bing Search Tool",+ "config": {+ "source_code": "async def bing_search(\n query: str,\n num_results: int = 3,\n include_snippets: bool = True,\n include_content: bool = True,\n content_max_length: Optional[int] = 10000,\n language: str = \"en\",\n country: Optional[str] = None,\n safe_search: str = \"moderate\",\n response_filter: str = \"webpages\",\n) -> List[Dict[str, str]]:\n \"\"\"\n Perform a Bing search using the Bing Web Search API.\n\n Args:\n query: Search query string\n num_results: Number of results to return (max 50)\n include_snippets: Include result snippets in output\n include_content: Include full webpage content in markdown format\n content_max_length: Maximum length of webpage content (if included)\n language: Language code for search results (e.g., 'en', 'es', 'fr')\n country: Optional market code for search results (e.g., 'us', 'uk')\n safe_search: SafeSearch setting ('off', 'moderate', or 'strict')\n response_filter: Type of results ('webpages', 'news', 'images', or 'videos')\n\n Returns:\n List[Dict[str, str]]: List of search results\n\n Raises:\n ValueError: If API credentials are invalid or request fails\n \"\"\"\n # Get and validate API key\n api_key = os.getenv(\"BING_SEARCH_KEY\", \"\").strip()\n\n if not api_key:\n raise ValueError(\n \"BING_SEARCH_KEY environment variable is not set. \" \"Please obtain an API key from Azure Portal.\"\n )\n\n # Validate safe_search parameter\n valid_safe_search = [\"off\", \"moderate\", \"strict\"]\n if safe_search.lower() not in valid_safe_search:\n raise ValueError(f\"Invalid safe_search value. Must be one of: {', '.join(valid_safe_search)}\")\n\n # Validate response_filter parameter\n valid_filters = [\"webpages\", \"news\", \"images\", \"videos\"]\n if response_filter.lower() not in valid_filters:\n raise ValueError(f\"Invalid response_filter value. Must be one of: {', '.join(valid_filters)}\")\n\n async def fetch_page_content(url: str, max_length: Optional[int] = 50000) -> str:\n \"\"\"Helper function to fetch and convert webpage content to markdown\"\"\"\n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\"}\n\n try:\n async with httpx.AsyncClient() as client:\n response = await client.get(url, headers=headers, timeout=10)\n response.raise_for_status()\n\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n # Remove script and style elements\n for script in soup([\"script\", \"style\"]):\n script.decompose()\n\n # Convert relative URLs to absolute\n for tag in soup.find_all([\"a\", \"img\"]):\n if tag.get(\"href\"):\n tag[\"href\"] = urljoin(url, tag[\"href\"])\n if tag.get(\"src\"):\n tag[\"src\"] = urljoin(url, tag[\"src\"])\n\n h2t = html2text.HTML2Text()\n h2t.body_width = 0\n h2t.ignore_images = False\n h2t.ignore_emphasis = False\n h2t.ignore_links = False\n h2t.ignore_tables = False\n\n markdown = h2t.handle(str(soup))\n\n if max_length and len(markdown) > max_length:\n markdown = markdown[:max_length] + \"\\n...(truncated)\"\n\n return markdown.strip()\n\n except Exception as e:\n return f\"Error fetching content: {str(e)}\"\n\n # Build request headers and parameters\n headers = {\"Ocp-Apim-Subscription-Key\": api_key, \"Accept\": \"application/json\"}\n\n params = {\n \"q\": query,\n \"count\": min(max(1, num_results), 50),\n \"mkt\": f\"{language}-{country.upper()}\" if country else language,\n \"safeSearch\": safe_search.capitalize(),\n \"responseFilter\": response_filter,\n \"textFormat\": \"raw\",\n }\n\n # Make the request\n try:\n async with httpx.AsyncClient() as client:\n response = await client.get(\n \"https://api.bing.microsoft.com/v7.0/search\", headers=headers, params=params, timeout=10\n )\n\n # Handle common error cases\n if response.status_code == 401:\n raise ValueError(\"Authentication failed. Please verify your Bing Search API key.\")\n elif response.status_code == 403:\n raise ValueError(\n \"Access forbidden. This could mean:\\n\"\n \"1. The API key is invalid\\n\"\n \"2. The API key has expired\\n\"\n \"3. You've exceeded your API quota\"\n )\n elif response.status_code == 429:\n raise ValueError(\"API quota exceeded. Please try again later.\")\n\n response.raise_for_status()\n data = response.json()\n\n # Process results based on response_filter\n results = []\n if response_filter == \"webpages\" and \"webPages\" in data:\n items = data[\"webPages\"][\"value\"]\n elif response_filter == \"news\" and \"news\" in data:\n items = data[\"news\"][\"value\"]\n elif response_filter == \"images\" and \"images\" in data:\n items = data[\"images\"][\"value\"]\n elif response_filter == \"videos\" and \"videos\" in data:\n items = data[\"videos\"][\"value\"]\n else:\n if not any(key in data for key in [\"webPages\", \"news\", \"images\", \"videos\"]):\n return [] # No results found\n raise ValueError(f\"No {response_filter} results found in API response\")\n\n # Extract relevant information based on result type\n for item in items:\n result = {\"title\": item.get(\"name\", \"\")}\n\n if response_filter == \"webpages\":\n result[\"link\"] = item.get(\"url\", \"\")\n if include_snippets:\n result[\"snippet\"] = item.get(\"snippet\", \"\")\n if include_content:\n result[\"content\"] = await fetch_page_content(result[\"link\"], max_length=content_max_length)\n\n elif response_filter == \"news\":\n result[\"link\"] = item.get(\"url\", \"\")\n if include_snippets:\n result[\"snippet\"] = item.get(\"description\", \"\")\n result[\"date\"] = item.get(\"datePublished\", \"\")\n if include_content:\n result[\"content\"] = await fetch_page_content(result[\"link\"], max_length=content_max_length)\n\n elif response_filter == \"images\":\n result[\"link\"] = item.get(\"contentUrl\", \"\")\n result[\"thumbnail\"] = item.get(\"thumbnailUrl\", \"\")\n if include_snippets:\n result[\"snippet\"] = item.get(\"description\", \"\")\n\n elif response_filter == \"videos\":\n result[\"link\"] = item.get(\"contentUrl\", \"\")\n result[\"thumbnail\"] = item.get(\"thumbnailUrl\", \"\")\n if include_snippets:\n result[\"snippet\"] = item.get(\"description\", \"\")\n result[\"duration\"] = item.get(\"duration\", \"\")\n\n results.append(result)\n\n return results[:num_results]\n\n except httpx.RequestException as e:\n error_msg = str(e)\n if \"InvalidApiKey\" in error_msg:\n raise ValueError(\"Invalid API key. Please check your BING_SEARCH_KEY environment variable.\") from e\n elif \"KeyExpired\" in error_msg:\n raise ValueError(\"API key has expired. Please generate a new key.\") from e\n else:\n raise ValueError(f\"Search request failed: {error_msg}\") from e\n except json.JSONDecodeError:\n raise ValueError(\"Failed to parse API response. \" \"Please verify your API credentials and try again.\") from None\n except Exception as e:\n raise ValueError(f\"Unexpected error during search: {str(e)}\") from e\n",+ "name": "bing_search",+ "description": "\n Perform Bing searches using the Bing Web Search API. Requires BING_SEARCH_KEY environment variable.\n Supports web, news, image, and video searches.\n See function documentation for detailed setup instructions.\n ",+ "global_imports": [+ {+ "module": "typing",+ "imports": ["List", "Dict", "Optional"]+ },+ "os",+ "httpx",+ "json",+ "html2text",+ {+ "module": "bs4",+ "imports": ["BeautifulSoup"]+ },+ {+ "module": "urllib.parse",+ "imports": ["urljoin"]+ }+ ],+ "has_cancellation_support": false+ }+ },+ {+ "provider": "autogen_core.tools.FunctionTool",+ "component_type": "tool",+ "version": 1,+ "component_version": 1,+ "description": "A tool that performs Google searches using the Google Custom Search API. Requires the requests library, [GOOGLE_API_KEY, GOOGLE_CSE_ID] to be set, env variable to function.",+ "label": "Google Search Tool",+ "config": {+ "source_code": "async def google_search(\n query: str,\n num_results: int = 3,\n include_snippets: bool = True,\n include_content: bool = True,\n content_max_length: Optional[int] = 10000,\n language: str = \"en\",\n country: Optional[str] = None,\n safe_search: bool = True,\n) -> List[Dict[str, str]]:\n \"\"\"\n Perform a Google search using the Custom Search API and optionally fetch webpage content.\n\n Args:\n query: Search query string\n num_results: Number of results to return (max 10)\n include_snippets: Include result snippets in output\n include_content: Include full webpage content in markdown format\n content_max_length: Maximum length of webpage content (if included)\n language: Language code for search results (e.g., en, es, fr)\n country: Optional country code for search results (e.g., us, uk)\n safe_search: Enable safe search filtering\n\n Returns:\n List[Dict[str, str]]: List of search results, each containing:\n - title: Result title\n - link: Result URL\n - snippet: Result description (if include_snippets=True)\n - content: Webpage content in markdown (if include_content=True)\n \"\"\"\n api_key = os.getenv(\"GOOGLE_API_KEY\")\n cse_id = os.getenv(\"GOOGLE_CSE_ID\")\n\n if not api_key or not cse_id:\n raise ValueError(\"Missing required environment variables. Please set GOOGLE_API_KEY and GOOGLE_CSE_ID.\")\n\n num_results = min(max(1, num_results), 10)\n\n async def fetch_page_content(url: str, max_length: Optional[int] = 50000) -> str:\n \"\"\"Helper function to fetch and convert webpage content to markdown\"\"\"\n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\"}\n\n try:\n async with httpx.AsyncClient() as client:\n response = await client.get(url, headers=headers, timeout=10)\n response.raise_for_status()\n\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n # Remove script and style elements\n for script in soup([\"script\", \"style\"]):\n script.decompose()\n\n # Convert relative URLs to absolute\n for tag in soup.find_all([\"a\", \"img\"]):\n if tag.get(\"href\"):\n tag[\"href\"] = urljoin(url, tag[\"href\"])\n if tag.get(\"src\"):\n tag[\"src\"] = urljoin(url, tag[\"src\"])\n\n h2t = html2text.HTML2Text()\n h2t.body_width = 0\n h2t.ignore_images = False\n h2t.ignore_emphasis = False\n h2t.ignore_links = False\n h2t.ignore_tables = False\n\n markdown = h2t.handle(str(soup))\n\n if max_length and len(markdown) > max_length:\n markdown = markdown[:max_length] + \"\\n...(truncated)\"\n\n return markdown.strip()\n\n except Exception as e:\n return f\"Error fetching content: {str(e)}\"\n\n params = {\n \"key\": api_key,\n \"cx\": cse_id,\n \"q\": query,\n \"num\": num_results,\n \"hl\": language,\n \"safe\": \"active\" if safe_search else \"off\",\n }\n\n if country:\n params[\"gl\"] = country\n\n try:\n async with httpx.AsyncClient() as client:\n response = await client.get(\"https://www.googleapis.com/customsearch/v1\", params=params, timeout=10)\n response.raise_for_status()\n data = response.json()\n\n results = []\n if \"items\" in data:\n for item in data[\"items\"]:\n result = {\"title\": item.get(\"title\", \"\"), \"link\": item.get(\"link\", \"\")}\n if include_snippets:\n result[\"snippet\"] = item.get(\"snippet\", \"\")\n\n if include_content:\n result[\"content\"] = await fetch_page_content(result[\"link\"], max_length=content_max_length)\n\n results.append(result)\n\n return results\n\n except httpx.RequestError as e:\n raise ValueError(f\"Failed to perform search: {str(e)}\") from e\n except KeyError as e:\n raise ValueError(f\"Invalid API response format: {str(e)}\") from e\n except Exception as e:\n raise ValueError(f\"Error during search: {str(e)}\") from e\n",+ "name": "google_search",+ "description": "\n Perform Google searches using the Custom Search API with optional webpage content fetching.\n Requires GOOGLE_API_KEY and GOOGLE_CSE_ID environment variables to be set.\n ",+ "global_imports": [+ {+ "module": "typing",+ "imports": ["List", "Dict", "Optional"]+ },+ "os",+ "httpx",+ "html2text",+ {+ "module": "bs4",+ "imports": ["BeautifulSoup"]+ },+ {+ "module": "urllib.parse",+ "imports": ["urljoin"]+ }+ ],+ "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,+ "include_agent_event": false+ }+ },+ {+ "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,+ "include_agent_event": false+ }+ }+ ]+ }+ }+ ],"teams": [{"provider": "autogen_agentchat.teams.RoundRobinGroupChat",@@ -652,438 +1082,6 @@"max_selector_attempts": 3}}- ],- "components": {- "agents": [- {- "provider": "autogen_agentchat.agents.AssistantAgent",- "component_type": "agent",- "version": 1,- "component_version": 1,- "description": "An agent that provides assistance with ability to use tools.",- "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": "OpenAI GPT-4o-mini",- "label": "OpenAI GPT-4o Mini",- "config": {- "model": "gpt-4o-mini"- }- },- {- "provider": "autogen_ext.models.openai.OpenAIChatCompletionClient",- "component_type": "model",- "version": 1,- "component_version": 1,- "description": "Local Mistral-7B model client for instruction-based generation (Ollama, LMStudio).",- "label": "Mistral-7B Local",- "config": {- "model": "TheBloke/Mistral-7B-Instruct-v0.2-GGUF",- "model_info": {- "vision": false,- "function_calling": true,- "json_output": false,- "family": "unknown"- },- "base_url": "http://localhost:1234/v1"- }- },- {- "provider": "autogen_ext.models.openai.AzureOpenAIChatCompletionClient",- "component_type": "model",- "version": 1,- "component_version": 1,- "description": "GPT-4o Mini Azure OpenAI model client.",- "label": "AzureOpenAI GPT-4o-mini",- "config": {- "model": "gpt-4o-mini",- "api_key": "sk-...",- "azure_endpoint": "https://{your-custom-endpoint}.openai.azure.com/",- "azure_deployment": "{your-azure-deployment}",- "api_version": "2024-06-01"- }- }- ],- "tools": [- {- "provider": "autogen_core.tools.FunctionTool",- "component_type": "tool",- "version": 1,- "component_version": 1,- "description": "A tool that performs basic arithmetic operations (addition, subtraction, multiplication, division).",- "label": "Calculator Tool",- "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- }- },- {- "provider": "autogen_core.tools.FunctionTool",- "component_type": "tool",- "version": 1,- "component_version": 1,- "description": "A tool that generates images based on a text description using OpenAI's DALL-E model. Note: Requires OpenAI API key to function.",- "label": "Image Generation Tool",- "config": {- "source_code": "async def generate_image(\n query: str, output_dir: Optional[Path] = None, image_size: Literal[\"1024x1024\", \"512x512\", \"256x256\"] = \"1024x1024\"\n) -> List[str]:\n \"\"\"\n Generate images using OpenAI's DALL-E model based on a text description.\n\n Args:\n query: Natural language description of the desired image\n output_dir: Directory to save generated images (default: current directory)\n image_size: Size of generated image (1024x1024, 512x512, or 256x256)\n\n Returns:\n List[str]: Paths to the generated image files\n \"\"\"\n # Initialize the OpenAI client\n client = OpenAI()\n\n # Generate images using DALL-E 3\n response = client.images.generate(model=\"dall-e-3\", prompt=query, n=1, response_format=\"b64_json\", size=image_size)\n\n saved_files = []\n\n # Process the response\n if response.data:\n for image_data in response.data:\n # Generate a unique filename\n file_name = f\"{uuid.uuid4()}.png\"\n\n # Use output_dir if provided, otherwise use current directory\n file_path = Path(output_dir) / file_name if output_dir else Path(file_name)\n\n base64_str = image_data.b64_json\n img = Image.open(io.BytesIO(base64.decodebytes(bytes(base64_str, \"utf-8\"))))\n\n # Save the image to a file\n img.save(file_path)\n\n saved_files.append(str(file_path))\n\n return saved_files\n",- "name": "generate_image",- "description": "Generate images using DALL-E based on text descriptions.",- "global_imports": [- "io",- "uuid",- "base64",- {- "module": "typing",- "imports": ["List", "Optional", "Literal"]- },- {- "module": "pathlib",- "imports": ["Path"]- },- {- "module": "openai",- "imports": ["OpenAI"]- },- {- "module": "PIL",- "imports": ["Image"]- }- ],- "has_cancellation_support": false- }- },- {- "provider": "autogen_core.tools.FunctionTool",- "component_type": "tool",- "version": 1,- "component_version": 1,- "description": "A tool that generates a PDF file from a list of images.Requires the PyFPDF and pillow library to function.",- "label": "PDF Generation Tool",- "config": {- "source_code": "async def generate_pdf(\n sections: List[Dict[str, Optional[str]]], output_file: str = \"report.pdf\", report_title: str = \"PDF Report\"\n) -> str:\n \"\"\"\n Generate a PDF report with formatted sections including text and images.\n\n Args:\n sections: List of dictionaries containing section details with keys:\n - title: Section title\n - level: Heading level (title, h1, h2)\n - content: Section text content\n - image: Optional image URL or file path\n output_file: Name of output PDF file\n report_title: Title shown at top of report\n\n Returns:\n str: Path to the generated PDF file\n \"\"\"\n\n def normalize_text(text: str) -> str:\n \"\"\"Normalize Unicode text to ASCII.\"\"\"\n return unicodedata.normalize(\"NFKD\", text).encode(\"ascii\", \"ignore\").decode(\"ascii\")\n\n def get_image(image_url_or_path):\n \"\"\"Fetch image from URL or local path.\"\"\"\n if image_url_or_path.startswith((\"http://\", \"https://\")):\n response = requests.get(image_url_or_path)\n if response.status_code == 200:\n return BytesIO(response.content)\n elif Path(image_url_or_path).is_file():\n return open(image_url_or_path, \"rb\")\n return None\n\n def add_rounded_corners(img, radius=6):\n \"\"\"Add rounded corners to an image.\"\"\"\n mask = Image.new(\"L\", img.size, 0)\n draw = ImageDraw.Draw(mask)\n draw.rounded_rectangle([(0, 0), img.size], radius, fill=255)\n img = ImageOps.fit(img, mask.size, centering=(0.5, 0.5))\n img.putalpha(mask)\n return img\n\n class PDF(FPDF):\n \"\"\"Custom PDF class with header and content formatting.\"\"\"\n\n def header(self):\n self.set_font(\"Arial\", \"B\", 12)\n normalized_title = normalize_text(report_title)\n self.cell(0, 10, normalized_title, 0, 1, \"C\")\n\n def chapter_title(self, txt):\n self.set_font(\"Arial\", \"B\", 12)\n normalized_txt = normalize_text(txt)\n self.cell(0, 10, normalized_txt, 0, 1, \"L\")\n self.ln(2)\n\n def chapter_body(self, body):\n self.set_font(\"Arial\", \"\", 12)\n normalized_body = normalize_text(body)\n self.multi_cell(0, 10, normalized_body)\n self.ln()\n\n def add_image(self, img_data):\n img = Image.open(img_data)\n img = add_rounded_corners(img)\n img_path = Path(f\"temp_{uuid.uuid4().hex}.png\")\n img.save(img_path, format=\"PNG\")\n self.image(str(img_path), x=None, y=None, w=190 if img.width > 190 else img.width)\n self.ln(10)\n img_path.unlink()\n\n # Initialize PDF\n pdf = PDF()\n pdf.add_page()\n font_size = {\"title\": 16, \"h1\": 14, \"h2\": 12, \"body\": 12}\n\n # Add sections\n for section in sections:\n title = section.get(\"title\", \"\")\n level = section.get(\"level\", \"h1\")\n content = section.get(\"content\", \"\")\n image = section.get(\"image\")\n\n pdf.set_font(\"Arial\", \"B\" if level in font_size else \"\", font_size.get(level, font_size[\"body\"]))\n pdf.chapter_title(title)\n\n if content:\n pdf.chapter_body(content)\n\n if image:\n img_data = get_image(image)\n if img_data:\n pdf.add_image(img_data)\n if isinstance(img_data, BytesIO):\n img_data.close()\n\n pdf.output(output_file)\n return output_file\n",- "name": "generate_pdf",- "description": "Generate PDF reports with formatted sections containing text and images",- "global_imports": [- "uuid",- "requests",- "unicodedata",- {- "module": "typing",- "imports": ["List", "Dict", "Optional"]- },- {- "module": "pathlib",- "imports": ["Path"]- },- {- "module": "fpdf",- "imports": ["FPDF"]- },- {- "module": "PIL",- "imports": ["Image", "ImageDraw", "ImageOps"]- },- {- "module": "io",- "imports": ["BytesIO"]- }- ],- "has_cancellation_support": false- }- },- {- "provider": "autogen_core.tools.FunctionTool",- "component_type": "tool",- "version": 1,- "component_version": 1,- "description": "A tool that fetches the content of a webpage and converts it to markdown. Requires the requests and beautifulsoup4 library to function.",- "label": "Fetch Webpage Tool",- "config": {- "source_code": "async def fetch_webpage(\n url: str, include_images: bool = True, max_length: Optional[int] = None, headers: Optional[Dict[str, str]] = None\n) -> str:\n \"\"\"Fetch a webpage and convert it to markdown format.\n\n Args:\n url: The URL of the webpage to fetch\n include_images: Whether to include image references in the markdown\n max_length: Maximum length of the output markdown (if None, no limit)\n headers: Optional HTTP headers for the request\n\n Returns:\n str: Markdown version of the webpage content\n\n Raises:\n ValueError: If the URL is invalid or the page can't be fetched\n \"\"\"\n # Use default headers if none provided\n if headers is None:\n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\"}\n\n try:\n # Fetch the webpage\n async with httpx.AsyncClient() as client:\n response = await client.get(url, headers=headers, timeout=10)\n response.raise_for_status()\n\n # Parse HTML\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n # Remove script and style elements\n for script in soup([\"script\", \"style\"]):\n script.decompose()\n\n # Convert relative URLs to absolute\n for tag in soup.find_all([\"a\", \"img\"]):\n if tag.get(\"href\"):\n tag[\"href\"] = urljoin(url, tag[\"href\"])\n if tag.get(\"src\"):\n tag[\"src\"] = urljoin(url, tag[\"src\"])\n\n # Configure HTML to Markdown converter\n h2t = html2text.HTML2Text()\n h2t.body_width = 0 # No line wrapping\n h2t.ignore_images = not include_images\n h2t.ignore_emphasis = False\n h2t.ignore_links = False\n h2t.ignore_tables = False\n\n # Convert to markdown\n markdown = h2t.handle(str(soup))\n\n # Trim if max_length is specified\n if max_length and len(markdown) > max_length:\n markdown = markdown[:max_length] + \"\\n...(truncated)\"\n\n return markdown.strip()\n\n except httpx.RequestError as e:\n raise ValueError(f\"Failed to fetch webpage: {str(e)}\") from e\n except Exception as e:\n raise ValueError(f\"Error processing webpage: {str(e)}\") from e\n",- "name": "fetch_webpage",- "description": "Fetch a webpage and convert it to markdown format, with options for including images and limiting length",- "global_imports": [- "os",- "html2text",- {- "module": "typing",- "imports": ["Optional", "Dict"]- },- "httpx",- {- "module": "bs4",- "imports": ["BeautifulSoup"]- },- {- "module": "html2text",- "imports": ["HTML2Text"]- },- {- "module": "urllib.parse",- "imports": ["urljoin"]- }- ],- "has_cancellation_support": false- }- },- {- "provider": "autogen_core.tools.FunctionTool",- "component_type": "tool",- "version": 1,- "component_version": 1,- "description": "A tool that performs Bing searches using the Bing Web Search API. Requires the requests library, BING_SEARCH_KEY env variable to function.",- "label": "Bing Search Tool",- "config": {- "source_code": "async def bing_search(\n query: str,\n num_results: int = 3,\n include_snippets: bool = True,\n include_content: bool = True,\n content_max_length: Optional[int] = 10000,\n language: str = \"en\",\n country: Optional[str] = None,\n safe_search: str = \"moderate\",\n response_filter: str = \"webpages\",\n) -> List[Dict[str, str]]:\n \"\"\"\n Perform a Bing search using the Bing Web Search API.\n\n Args:\n query: Search query string\n num_results: Number of results to return (max 50)\n include_snippets: Include result snippets in output\n include_content: Include full webpage content in markdown format\n content_max_length: Maximum length of webpage content (if included)\n language: Language code for search results (e.g., 'en', 'es', 'fr')\n country: Optional market code for search results (e.g., 'us', 'uk')\n safe_search: SafeSearch setting ('off', 'moderate', or 'strict')\n response_filter: Type of results ('webpages', 'news', 'images', or 'videos')\n\n Returns:\n List[Dict[str, str]]: List of search results\n\n Raises:\n ValueError: If API credentials are invalid or request fails\n \"\"\"\n # Get and validate API key\n api_key = os.getenv(\"BING_SEARCH_KEY\", \"\").strip()\n\n if not api_key:\n raise ValueError(\n \"BING_SEARCH_KEY environment variable is not set. \" \"Please obtain an API key from Azure Portal.\"\n )\n\n # Validate safe_search parameter\n valid_safe_search = [\"off\", \"moderate\", \"strict\"]\n if safe_search.lower() not in valid_safe_search:\n raise ValueError(f\"Invalid safe_search value. Must be one of: {', '.join(valid_safe_search)}\")\n\n # Validate response_filter parameter\n valid_filters = [\"webpages\", \"news\", \"images\", \"videos\"]\n if response_filter.lower() not in valid_filters:\n raise ValueError(f\"Invalid response_filter value. Must be one of: {', '.join(valid_filters)}\")\n\n async def fetch_page_content(url: str, max_length: Optional[int] = 50000) -> str:\n \"\"\"Helper function to fetch and convert webpage content to markdown\"\"\"\n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\"}\n\n try:\n async with httpx.AsyncClient() as client:\n response = await client.get(url, headers=headers, timeout=10)\n response.raise_for_status()\n\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n # Remove script and style elements\n for script in soup([\"script\", \"style\"]):\n script.decompose()\n\n # Convert relative URLs to absolute\n for tag in soup.find_all([\"a\", \"img\"]):\n if tag.get(\"href\"):\n tag[\"href\"] = urljoin(url, tag[\"href\"])\n if tag.get(\"src\"):\n tag[\"src\"] = urljoin(url, tag[\"src\"])\n\n h2t = html2text.HTML2Text()\n h2t.body_width = 0\n h2t.ignore_images = False\n h2t.ignore_emphasis = False\n h2t.ignore_links = False\n h2t.ignore_tables = False\n\n markdown = h2t.handle(str(soup))\n\n if max_length and len(markdown) > max_length:\n markdown = markdown[:max_length] + \"\\n...(truncated)\"\n\n return markdown.strip()\n\n except Exception as e:\n return f\"Error fetching content: {str(e)}\"\n\n # Build request headers and parameters\n headers = {\"Ocp-Apim-Subscription-Key\": api_key, \"Accept\": \"application/json\"}\n\n params = {\n \"q\": query,\n \"count\": min(max(1, num_results), 50),\n \"mkt\": f\"{language}-{country.upper()}\" if country else language,\n \"safeSearch\": safe_search.capitalize(),\n \"responseFilter\": response_filter,\n \"textFormat\": \"raw\",\n }\n\n # Make the request\n try:\n async with httpx.AsyncClient() as client:\n response = await client.get(\n \"https://api.bing.microsoft.com/v7.0/search\", headers=headers, params=params, timeout=10\n )\n\n # Handle common error cases\n if response.status_code == 401:\n raise ValueError(\"Authentication failed. Please verify your Bing Search API key.\")\n elif response.status_code == 403:\n raise ValueError(\n \"Access forbidden. This could mean:\\n\"\n \"1. The API key is invalid\\n\"\n \"2. The API key has expired\\n\"\n \"3. You've exceeded your API quota\"\n )\n elif response.status_code == 429:\n raise ValueError(\"API quota exceeded. Please try again later.\")\n\n response.raise_for_status()\n data = response.json()\n\n # Process results based on response_filter\n results = []\n if response_filter == \"webpages\" and \"webPages\" in data:\n items = data[\"webPages\"][\"value\"]\n elif response_filter == \"news\" and \"news\" in data:\n items = data[\"news\"][\"value\"]\n elif response_filter == \"images\" and \"images\" in data:\n items = data[\"images\"][\"value\"]\n elif response_filter == \"videos\" and \"videos\" in data:\n items = data[\"videos\"][\"value\"]\n else:\n if not any(key in data for key in [\"webPages\", \"news\", \"images\", \"videos\"]):\n return [] # No results found\n raise ValueError(f\"No {response_filter} results found in API response\")\n\n # Extract relevant information based on result type\n for item in items:\n result = {\"title\": item.get(\"name\", \"\")}\n\n if response_filter == \"webpages\":\n result[\"link\"] = item.get(\"url\", \"\")\n if include_snippets:\n result[\"snippet\"] = item.get(\"snippet\", \"\")\n if include_content:\n result[\"content\"] = await fetch_page_content(result[\"link\"], max_length=content_max_length)\n\n elif response_filter == \"news\":\n result[\"link\"] = item.get(\"url\", \"\")\n if include_snippets:\n result[\"snippet\"] = item.get(\"description\", \"\")\n result[\"date\"] = item.get(\"datePublished\", \"\")\n if include_content:\n result[\"content\"] = await fetch_page_content(result[\"link\"], max_length=content_max_length)\n\n elif response_filter == \"images\":\n result[\"link\"] = item.get(\"contentUrl\", \"\")\n result[\"thumbnail\"] = item.get(\"thumbnailUrl\", \"\")\n if include_snippets:\n result[\"snippet\"] = item.get(\"description\", \"\")\n\n elif response_filter == \"videos\":\n result[\"link\"] = item.get(\"contentUrl\", \"\")\n result[\"thumbnail\"] = item.get(\"thumbnailUrl\", \"\")\n if include_snippets:\n result[\"snippet\"] = item.get(\"description\", \"\")\n result[\"duration\"] = item.get(\"duration\", \"\")\n\n results.append(result)\n\n return results[:num_results]\n\n except httpx.RequestException as e:\n error_msg = str(e)\n if \"InvalidApiKey\" in error_msg:\n raise ValueError(\"Invalid API key. Please check your BING_SEARCH_KEY environment variable.\") from e\n elif \"KeyExpired\" in error_msg:\n raise ValueError(\"API key has expired. Please generate a new key.\") from e\n else:\n raise ValueError(f\"Search request failed: {error_msg}\") from e\n except json.JSONDecodeError:\n raise ValueError(\"Failed to parse API response. \" \"Please verify your API credentials and try again.\") from None\n except Exception as e:\n raise ValueError(f\"Unexpected error during search: {str(e)}\") from e\n",- "name": "bing_search",- "description": "\n Perform Bing searches using the Bing Web Search API. Requires BING_SEARCH_KEY environment variable.\n Supports web, news, image, and video searches.\n See function documentation for detailed setup instructions.\n ",- "global_imports": [- {- "module": "typing",- "imports": ["List", "Dict", "Optional"]- },- "os",- "httpx",- "json",- "html2text",- {- "module": "bs4",- "imports": ["BeautifulSoup"]- },- {- "module": "urllib.parse",- "imports": ["urljoin"]- }- ],- "has_cancellation_support": false- }- },- {- "provider": "autogen_core.tools.FunctionTool",- "component_type": "tool",- "version": 1,- "component_version": 1,- "description": "A tool that performs Google searches using the Google Custom Search API. Requires the requests library, [GOOGLE_API_KEY, GOOGLE_CSE_ID] to be set, env variable to function.",- "label": "Google Search Tool",- "config": {- "source_code": "async def google_search(\n query: str,\n num_results: int = 3,\n include_snippets: bool = True,\n include_content: bool = True,\n content_max_length: Optional[int] = 10000,\n language: str = \"en\",\n country: Optional[str] = None,\n safe_search: bool = True,\n) -> List[Dict[str, str]]:\n \"\"\"\n Perform a Google search using the Custom Search API and optionally fetch webpage content.\n\n Args:\n query: Search query string\n num_results: Number of results to return (max 10)\n include_snippets: Include result snippets in output\n include_content: Include full webpage content in markdown format\n content_max_length: Maximum length of webpage content (if included)\n language: Language code for search results (e.g., en, es, fr)\n country: Optional country code for search results (e.g., us, uk)\n safe_search: Enable safe search filtering\n\n Returns:\n List[Dict[str, str]]: List of search results, each containing:\n - title: Result title\n - link: Result URL\n - snippet: Result description (if include_snippets=True)\n - content: Webpage content in markdown (if include_content=True)\n \"\"\"\n api_key = os.getenv(\"GOOGLE_API_KEY\")\n cse_id = os.getenv(\"GOOGLE_CSE_ID\")\n\n if not api_key or not cse_id:\n raise ValueError(\"Missing required environment variables. Please set GOOGLE_API_KEY and GOOGLE_CSE_ID.\")\n\n num_results = min(max(1, num_results), 10)\n\n async def fetch_page_content(url: str, max_length: Optional[int] = 50000) -> str:\n \"\"\"Helper function to fetch and convert webpage content to markdown\"\"\"\n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\"}\n\n try:\n async with httpx.AsyncClient() as client:\n response = await client.get(url, headers=headers, timeout=10)\n response.raise_for_status()\n\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n # Remove script and style elements\n for script in soup([\"script\", \"style\"]):\n script.decompose()\n\n # Convert relative URLs to absolute\n for tag in soup.find_all([\"a\", \"img\"]):\n if tag.get(\"href\"):\n tag[\"href\"] = urljoin(url, tag[\"href\"])\n if tag.get(\"src\"):\n tag[\"src\"] = urljoin(url, tag[\"src\"])\n\n h2t = html2text.HTML2Text()\n h2t.body_width = 0\n h2t.ignore_images = False\n h2t.ignore_emphasis = False\n h2t.ignore_links = False\n h2t.ignore_tables = False\n\n markdown = h2t.handle(str(soup))\n\n if max_length and len(markdown) > max_length:\n markdown = markdown[:max_length] + \"\\n...(truncated)\"\n\n return markdown.strip()\n\n except Exception as e:\n return f\"Error fetching content: {str(e)}\"\n\n params = {\n \"key\": api_key,\n \"cx\": cse_id,\n \"q\": query,\n \"num\": num_results,\n \"hl\": language,\n \"safe\": \"active\" if safe_search else \"off\",\n }\n\n if country:\n params[\"gl\"] = country\n\n try:\n async with httpx.AsyncClient() as client:\n response = await client.get(\"https://www.googleapis.com/customsearch/v1\", params=params, timeout=10)\n response.raise_for_status()\n data = response.json()\n\n results = []\n if \"items\" in data:\n for item in data[\"items\"]:\n result = {\"title\": item.get(\"title\", \"\"), \"link\": item.get(\"link\", \"\")}\n if include_snippets:\n result[\"snippet\"] = item.get(\"snippet\", \"\")\n\n if include_content:\n result[\"content\"] = await fetch_page_content(result[\"link\"], max_length=content_max_length)\n\n results.append(result)\n\n return results\n\n except httpx.RequestError as e:\n raise ValueError(f\"Failed to perform search: {str(e)}\") from e\n except KeyError as e:\n raise ValueError(f\"Invalid API response format: {str(e)}\") from e\n except Exception as e:\n raise ValueError(f\"Error during search: {str(e)}\") from e\n",- "name": "google_search",- "description": "\n Perform Google searches using the Custom Search API with optional webpage content fetching.\n Requires GOOGLE_API_KEY and GOOGLE_CSE_ID environment variables to be set.\n ",- "global_imports": [- {- "module": "typing",- "imports": ["List", "Dict", "Optional"]- },- "os",- "httpx",- "html2text",- {- "module": "bs4",- "imports": ["BeautifulSoup"]- },- {- "module": "urllib.parse",- "imports": ["urljoin"]- }- ],- "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,- "include_agent_event": false- }- },- {- "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,- "include_agent_event": false- }- }- ]- }- }- ]- }+ ]}}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 0eb23391f..88942fd44 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@@ -1,170 +1,228 @@-import React, { useState, useRef } from "react";-import { Button, message, Tooltip } from "antd";+import React, { useState } from "react";+import { Tabs, Button, Tooltip, Drawer } from "antd";import {Package,Users,Bot,Globe,- RefreshCw,- Edit2,- X,Wrench,Brain,Timer,- Save,- ChevronUp,- ChevronDown,Edit,+ Copy,+ Trash,} from "lucide-react";+import { ComponentEditor } from "../team/builder/component-editor/component-editor";+import { TruncatableText } from "../atoms";import type { Gallery } from "./types";-import { useGalleryStore } from "./store";-import { MonacoEditor } from "../monaco";-import { getRelativeTimeString, TruncatableText } from "../atoms";-import { Component, ComponentConfig } from "../../types/datamodel";+import {+ Component,+ ComponentConfig,+ ComponentTypes,+} from "../../types/datamodel";-const ComponentGrid: React.FC<{- title: string;- icon: React.ReactNode;- items: Component<ComponentConfig>[];-}> = ({ title, icon, items }) => {- const [isExpanded, setIsExpanded] = useState(true);+type CategoryKey = `${ComponentTypes}s`;- return (- <div className="bg-tertiary rounded p-2">- <div- className="flex items-center justify-between cursor-pointer mb-2"- onClick={() => setIsExpanded(!isExpanded)}- >- <div className="flex items-center gap-2">- <span className="text-primary">{icon}</span>- <span className="text-sm capitalize">- {items.length} {items.length === 1 ? title : `${title}s`}- </span>- </div>- {isExpanded ? (- <ChevronUp className="w-4 h-4 text-primary" />- ) : (- <ChevronDown className="w-4 h-4 text-primary" />- )}- </div>+interface CardActions {+ onEdit: (component: Component<ComponentConfig>, index: number) => void;+ onDuplicate: (component: Component<ComponentConfig>, index: number) => void;+ onDelete: (component: Component<ComponentConfig>, index: number) => void;+}- <div- className={`space-y-2 transition-all duration-200 ${- isExpanded ? "max-h-[500px]" : "max-h-0"- } overflow-hidden`}- >- {items.map((item, idx) => (- <div- key={idx}- className="bg-secondary rounded p-3 hover:bg-tertiary transition-colors"- >- <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 && (- <div className="text-xs text-primary mt-1 ">- <TruncatableText- content={item.description}- textThreshold={150}- />- </div>- )}- </div>- ))}+// Component Card+const ComponentCard: React.FC<+ CardActions & {+ item: Component<ComponentConfig>;+ index: number;+ }+> = ({ item, onEdit, onDuplicate, onDelete, index }) => (+ <div+ className="bg-secondary rounded overflow-hidden group h-full cursor-pointer"+ onClick={() => onEdit(item, index)}+ >+ <div className="px-4 py-3 flex items-center justify-between border-b border-tertiary">+ <div className="text-xs text-secondary truncate flex-1">+ {item.provider}+ </div>+ <div className="flex gap-0">+ <Button+ title="Delete"+ type="text"+ className="h-6 w-6 flex items-center justify-center p-0 opacity-0 group-hover:opacity-100 transition-opacity text-red-500 hover:text-red-600"+ icon={<Trash className="w-3.5 h-3.5" />}+ onClick={(e) => {+ e.stopPropagation();+ onDelete(item, index);+ }}+ />+ <Button+ title="Duplicate"+ type="text"+ className="h-6 w-6 flex items-center justify-center p-0 opacity-0 group-hover:opacity-100 transition-opacity"+ icon={<Copy className="w-3.5 h-3.5" />}+ onClick={(e) => {+ e.stopPropagation();+ onDuplicate(item, index);+ }}+ />+ <Button+ title="Edit"+ type="text"+ className="h-6 w-6 flex items-center justify-center p-0 opacity-0 group-hover:opacity-100 transition-opacity"+ icon={<Edit className="w-3.5 h-3.5" />}+ onClick={(e) => {+ e.stopPropagation();+ onEdit(item, index);+ }}+ /></div></div>- );-};+ <div className="p-4 pb-0 pt-3">+ <div className="text-base font-medium mb-2">{item.label}</div>+ <div className="text-sm text-secondary line-clamp-2 mb-3 min-h-[40px]">+ <TruncatableText+ content={item.description || ""}+ showFullscreen={false}+ textThreshold={70}+ />+ </div>+ </div>+ </div>+);-interface GalleryDetailProps {+// Component Grid+const ComponentGrid: React.FC<+ {+ items: Component<ComponentConfig>[];+ title: string;+ } & CardActions+> = ({ items, title, ...actions }) => (+ <div>+ <h3 className="text-base font-medium m-0 mb-4">+ {items.length} {items.length === 1 ? title : `${title}s`}+ </h3>+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 auto-rows-fr">+ {items.map((item, idx) => (+ <ComponentCard key={idx} item={item} index={idx} {...actions} />+ ))}+ </div>+ </div>+);++const iconMap = {+ team: Users,+ agent: Bot,+ tool: Wrench,+ model: Brain,+ termination: Timer,+} as const;++export const GalleryDetail: React.FC<{gallery: Gallery;onSave: (updates: Partial<Gallery>) => void;onDirtyStateChange: (isDirty: boolean) => void;-}+}> = ({ gallery, onSave, onDirtyStateChange }) => {+ const [editingComponent, setEditingComponent] = useState<{+ component: Component<ComponentConfig>;+ category: CategoryKey;+ index: number;+ } | null>(null);+ const [activeTab, setActiveTab] = useState<ComponentTypes>("team");++ const updateGallery = (+ category: CategoryKey,+ updater: (+ components: Component<ComponentConfig>[]+ ) => Component<ComponentConfig>[]+ ) => {+ const updatedGallery = {+ ...gallery,+ components: {+ ...gallery.components,+ [category]: updater(gallery.components[category]),+ },+ };+ onSave(updatedGallery);+ onDirtyStateChange(true);+ };-export const GalleryDetail: React.FC<GalleryDetailProps> = ({- gallery,- onSave,- onDirtyStateChange,-}) => {- const [isEditing, setIsEditing] = useState(false);- const [isSyncing, setIsSyncing] = useState(false);- const [jsonValue, setJsonValue] = useState(JSON.stringify(gallery, null, 2));- const editorRef = useRef(null);- const { syncGallery, getLastSyncTime } = useGalleryStore();+ const handlers = {+ onEdit: (component: Component<ComponentConfig>, index: number) => {+ setEditingComponent({+ component,+ category: `${activeTab}s` as CategoryKey,+ index,+ });+ },- const handleSync = async () => {- if (!gallery.url) return;+ onDuplicate: (component: Component<ComponentConfig>, index: number) => {+ const category = `${activeTab}s` as CategoryKey;+ const baseLabel = component.label?.replace(/_\d+$/, "");+ const components = gallery.components[category];- setIsSyncing(true);- try {- await syncGallery(gallery.id);- message.success("Gallery synced successfully");- } catch (error) {- message.error("Failed to sync gallery");- } finally {- setIsSyncing(false);- }- };+ const nextNumber =+ Math.max(+ ...components+ .map((c) => {+ const match = c.label?.match(+ new RegExp(`^${baseLabel}_?(\\d+)?$`)+ );+ return match ? parseInt(match[1] || "0") : 0;+ })+ .filter((n) => !isNaN(n)),+ 0+ ) + 1;- const handleJsonChange = (value: string) => {- setJsonValue(value);- onDirtyStateChange(true);+ updateGallery(category, (components) => [+ ...components,+ { ...component, label: `${baseLabel}_${nextNumber}` },+ ]);+ },++ onDelete: (component: Component<ComponentConfig>, index: number) => {+ const category = `${activeTab}s` as CategoryKey;+ updateGallery(category, (components) =>+ components.filter((_, i) => i !== index)+ );+ },};- const handleSave = async () => {- try {- const parsedGallery = JSON.parse(jsonValue);- const updatedGallery = {- ...parsedGallery,- id: gallery.id,- metadata: {- ...parsedGallery.metadata,- updated_at: new Date().toISOString(),- },- };- await onSave(updatedGallery);- onDirtyStateChange(false);- setIsEditing(false);- message.success("Gallery updated successfully");- } catch (error) {- message.error("Invalid JSON format");- }+ const handleComponentUpdate = (+ updatedComponent: Component<ComponentConfig>+ ) => {+ if (!editingComponent) return;++ updateGallery(editingComponent.category, (components) =>+ components.map((c, i) =>+ i === editingComponent.index ? updatedComponent : c+ )+ );+ setEditingComponent(null);};- const gridItems = [- {- icon: <Users className="w-4 h-4" />,- title: "team",- items: gallery.items.teams,- },- {- icon: <Bot className="w-4 h-4" />,- title: "agent",- items: gallery.items.components.agents,- },- {- icon: <Wrench className="w-4 h-4" />,- title: "tool",- items: gallery.items.components.tools,- },- {- icon: <Brain className="w-4 h-4" />,- title: "model",- items: gallery.items.components.models,- },- {- icon: <Timer className="w-4 h-4" />,- title: "termination",- items: gallery.items.components.terminations,- },- ];+ const tabItems = Object.entries(iconMap).map(([key, Icon]) => ({+ key,+ label: (+ <span className="flex items-center gap-2">+ <Icon className="w-5 h-5" />+ {key.charAt(0).toUpperCase() + key.slice(1)}s+ <span className="text-xs font-light text-secondary">+ ({gallery.components[`${key}s` as CategoryKey].length})+ </span>+ </span>+ ),+ children: (+ <ComponentGrid+ items={gallery.components[`${key}s` as CategoryKey]}+ title={key}+ {...handlers}+ />+ ),+ }));return (- <div className="space-y-6">- {/* Banner Section - Kept unchanged */}- <div className="relative h-72 rounded bg-secondary overflow-hidden">+ <div className="max-w-7xl mx-auto px-4">+ <div className="relative h-64 rounded bg-secondary overflow-hidden mb-8"><imgsrc="/images/bg/layeredbg.svg"alt="Gallery Banner"@@ -182,19 +240,15 @@ export const GalleryDetail: React.FC<GalleryDetailProps> = ({</Tooltip>)}</div>- <p className="text-secondary w-1/2 mt-2 line-clamp-3">+ <p className="text-secondary w-1/2 mt-2 line-clamp-2">{gallery.metadata.description}</p>- <p className="text-secondary text-sm mt-2">- {gallery.metadata.author}- </p></div>-<div className="flex gap-2"><div className="bg-tertiary backdrop-blur rounded p-2 flex items-center gap-2"><Package className="w-4 h-4 text-secondary" /><span className="text-sm">- {Object.values(gallery.items.components).reduce(+ {Object.values(gallery.components).reduce((sum, arr) => sum + arr.length,0)}{" "}@@ -204,113 +258,36 @@ export const GalleryDetail: React.FC<GalleryDetailProps> = ({<div className="bg-tertiary backdrop-blur rounded p-2 text-sm">v{gallery.metadata.version}</div>- {gallery.metadata.tags?.map((tag) => (- <div- key={tag}- className="bg-tertiary backdrop-blur rounded p-2 px-2 text-sm"- >- {tag}- </div>- ))}</div></div></div>- {/* Action Buttons */}- <div className="flex justify-end gap-2">- {gallery.url && (- <Tooltip- title={- getLastSyncTime(gallery.id)- ? `Last synced: ${getRelativeTimeString(- getLastSyncTime(gallery.id) || ""- )}`- : "Never synced"- }- >- <Button- icon={- <RefreshCw- className={(isSyncing ? "animate-spin" : "") + " w-4 h-4"}- />- }- loading={isSyncing}- onClick={handleSync}- >- Sync- </Button>- </Tooltip>- )}- {!isEditing ? (- <Button- icon={<Edit className="w-4 h-4" />}- onClick={() => setIsEditing(true)}- >- Edit- </Button>- ) : (- <>- <Button- icon={<X className="w-4 h-4" />}- onClick={() => setIsEditing(false)}- >- Cancel- </Button>- <Button type="primary" onClick={handleSave}>- Save Changes- </Button>- </>- )}- </div>+ <Tabs+ items={tabItems}+ className="gallery-tabs"+ size="large"+ onChange={(key) => setActiveTab(key as ComponentTypes)}+ />- {/* Grid Layout */}- <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">- {gridItems.map((item) => (- <ComponentGrid- key={item.title}- title={item.title}- icon={item.icon}- items={item.items}+ <Drawer+ title="Edit Component"+ placement="right"+ size="large"+ onClose={() => setEditingComponent(null)}+ open={!!editingComponent}+ className="component-editor-drawer"+ >+ {editingComponent && (+ <ComponentEditor+ component={editingComponent.component}+ onChange={handleComponentUpdate}+ onClose={() => setEditingComponent(null)}+ navigationDepth={true}/>- ))}- </div>-- {/* Editor Section */}- {isEditing && (- <div- className="fixed bottom-0 left-0 right-0 bg-primary z-50 shadow-lg transition-transform duration-300 ease-in-out transform"- style={{ height: "70vh" }}- >- <div className="border-b border-secondary p-4 flex justify-between items-center">- <h3 className="text-normal font-medium">- Edit Gallery Configuration- </h3>- <div className="inline-flex gap-2">- <Tooltip title="Save Changes">- <Button- icon={<Save className="w-4 h-4" />}- onClick={handleSave}- />- </Tooltip>- <Tooltip title="Cancel Editing">- <Button- icon={<X className="w-4 h-4" />}- onClick={() => setIsEditing(false)}- />- </Tooltip>- </div>- </div>- <div className="h-[calc(100%-60px)]">- <MonacoEditor- value={jsonValue}- onChange={handleJsonChange}- editorRef={editorRef}- language="json"- minimap={true}- />- </div>- </div>- )}+ )}+ </Drawer></div>);};++export default GalleryDetail;diff --git a/python/packages/autogen-studio/frontend/src/components/views/gallery/manager.tsx b/python/packages/autogen-studio/frontend/src/components/views/gallery/manager.tsxindex 7dd8e15cd..dbbc40a14 100644--- a/python/packages/autogen-studio/frontend/src/components/views/gallery/manager.tsx+++ b/python/packages/autogen-studio/frontend/src/components/views/gallery/manager.tsx@@ -85,14 +85,12 @@ export const GalleryManager: React.FC = () => {created_at: new Date().toISOString(),updated_at: new Date().toISOString(),},- items: galleryData.items || {+ components: galleryData.components || {teams: [],- components: {- agents: [],- models: [],- tools: [],- terminations: [],- },+ agents: [],+ models: [],+ tools: [],+ terminations: [],},};diff --git a/python/packages/autogen-studio/frontend/src/components/views/gallery/sidebar.tsx b/python/packages/autogen-studio/frontend/src/components/views/gallery/sidebar.tsxindex d37567715..a58908c0a 100644--- a/python/packages/autogen-studio/frontend/src/components/views/gallery/sidebar.tsx+++ b/python/packages/autogen-studio/frontend/src/components/views/gallery/sidebar.tsx@@ -237,7 +237,7 @@ export const GallerySidebar: React.FC<GallerySidebarProps> = ({<div className="flex items-center gap-1"><Package className="w-3 h-3" /><span>- {Object.values(gallery.items.components).reduce(+ {Object.values(gallery.components).reduce((sum, arr) => sum + arr.length,0)}{" "}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 604d4e57e..951c5e225 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@@ -145,13 +145,18 @@ export const useGalleryStore = create<GalleryStore>()(getGalleryComponents: () => {const defaultGallery = get().getDefaultGallery();return {- teams: defaultGallery.items.teams,- components: defaultGallery.items.components,+ teams: defaultGallery.components.teams,+ components: {+ agents: defaultGallery.components.agents,+ models: defaultGallery.components.models,+ tools: defaultGallery.components.tools,+ terminations: defaultGallery.components.terminations,+ },};},}),{- name: "gallery-storage-v7",+ name: "gallery-storage-v8",}));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 7db306b90..479d89af5 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@@ -25,14 +25,12 @@ export interface Gallery {name: string;url?: string;metadata: GalleryMetadata;- items: {+ components: {teams: Component<TeamConfig>[];- components: {- agents: Component<AgentConfig>[];- models: Component<ModelConfig>[];- tools: Component<ToolConfig>[];- terminations: Component<TerminationConfig>[];- };+ agents: Component<AgentConfig>[];+ models: Component<ModelConfig>[];+ tools: Component<ToolConfig>[];+ terminations: Component<TerminationConfig>[];};}diff --git a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/logrenderer.tsx b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/logrenderer.tsxindex 6a34f8a8e..9942c583b 100644--- a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/logrenderer.tsx+++ b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/logrenderer.tsx@@ -57,7 +57,7 @@ const FullLogView = ({<Tooltip title="Close"><buttononClick={onClose}- className="absolute top-4 right-4 p-2 rounded-full bg-black/50 hover:bg-black/70 text-primary transition-colors"+ className="absolute top-4 right-4 p-2 rounded-full bg-tertiary hover:bg-secondary text-primary transition-colors"><X size={24} /></button>@@ -79,14 +79,19 @@ const FullLogView = ({<div key={idx} className="p-4 bg-tertiary rounded-lg"><div className="flex justify-between mb-2"><span className="text-xs font-medium uppercase text-secondary">- {msg.role} {msg.name && `(${msg.name})`}+ {(msg.name && `${msg.name}`) || msg.role}{" "}+ {Array.isArray(msg.content) + " array "}</span></div>- <TruncatableText- content={msg.content}- textThreshold={1000}- showFullscreen={false}- />+ {Array.isArray(msg.content) ? (+ msg.content.map((item, index) => (+ <div key={index} className="text-sm text-secondary">+ <TruncatableText content={item} showFullscreen={false} />+ </div>+ ))+ ) : (+ <TruncatableText content={msg.content} showFullscreen={false} />+ )}</div>))}</div>@@ -142,6 +147,8 @@ const LLMLogRenderer: React.FC<LLMLogRendererProps> = ({ content }) => {}}, [content]);+ console.log(parsedContent);+if (!parsedContent) {return (<div className="flex items-center gap-2 text-red-500 p-2 bg-red-500/10 rounded">diff --git a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/rendermessage.tsx b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/rendermessage.tsxindex 2041a1a1a..e9025e2f1 100644--- a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/rendermessage.tsx+++ b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/rendermessage.tsx@@ -1,12 +1,5 @@-import React, { useState, memo } from "react";-import {- User,- Bot,- Maximize2,- Minimize2,- DraftingCompass,- Brain,-} from "lucide-react";+import React from "react";+import { User, Bot, DraftingCompass, Bug } from "lucide-react";import {AgentMessageConfig,FunctionCall,@@ -176,7 +169,7 @@ export const RenderMessage: React.FC<MessageProps> = ({{isUser ? (<User size={14} />) : message.source == "llm_call_event" ? (- <Brain size={14} />+ <Bug size={14} />) : (<Bot size={14} />)}diff --git a/python/packages/autogen-studio/frontend/src/components/views/playground/manager.tsx b/python/packages/autogen-studio/frontend/src/components/views/playground/manager.tsxindex 97be1dd0d..c0be689ee 100644--- a/python/packages/autogen-studio/frontend/src/components/views/playground/manager.tsx+++ b/python/packages/autogen-studio/frontend/src/components/views/playground/manager.tsx@@ -196,7 +196,7 @@ export const SessionManager: React.FC = () => {if (teamsData.length > 0) {setTeams(teamsData);} else {- const sampleTeam = defaultGallery.items.teams[0];+ const sampleTeam = defaultGallery.components.teams[0];// If no teams, create a default teamconst defaultTeam = await teamAPI.createTeam({diff --git a/python/packages/autogen-studio/frontend/src/components/views/settings/manager.tsx b/python/packages/autogen-studio/frontend/src/components/views/settings/manager.tsxindex fbae94e50..0ab511e79 100644--- a/python/packages/autogen-studio/frontend/src/components/views/settings/manager.tsx+++ b/python/packages/autogen-studio/frontend/src/components/views/settings/manager.tsx@@ -26,7 +26,7 @@ const SettingToggle: React.FC<SettingToggleProps> = ({label,description,}) => (- <div className="flex justify-between items-start p-4 hover:bg-secondary/5 rounded-lg transition-colors">+ <div className="flex justify-between items-start p-4 hover:bg-secondary/5 rounded transition-colors"><div className="flex flex-col gap-1"><label className="font-medium">{label}</label>{description && (@@ -85,7 +85,7 @@ export const SettingsManager: React.FC = () => {icon={MessagesSquare}onReset={resetPlaygroundSettings}/>- <div className="space-y-2 rounded-xl border border-secondary">+ <div className="space-y-2 rounded border border-secondary"><SettingTogglechecked={playground.showLLMEvents}onChange={(checked) =>diff --git a/python/packages/autogen-studio/frontend/src/components/views/team/api.ts b/python/packages/autogen-studio/frontend/src/components/views/team/api.tsindex 65ff98b28..c3059d8c9 100644--- a/python/packages/autogen-studio/frontend/src/components/views/team/api.ts+++ b/python/packages/autogen-studio/frontend/src/components/views/team/api.ts@@ -107,7 +107,7 @@ export class ValidationAPI {async validateComponent(component: Component<ComponentConfig>): Promise<ValidationResponse> {- const response = await fetch(`${this.getBaseUrl()}/validate`, {+ const response = await fetch(`${this.getBaseUrl()}/validate/`, {method: "POST",headers: this.getHeaders(),body: JSON.stringify({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 335c4e9f1..5a8159b4c 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@@ -20,7 +20,7 @@ import {MiniMap,} from "@xyflow/react";import "@xyflow/react/dist/style.css";-import { Button, Layout, message, Switch, Tooltip } from "antd";+import { Button, Drawer, Layout, message, Switch, Tooltip } from "antd";import {Cable,CheckCircle,@@ -41,11 +41,11 @@ import { edgeTypes, nodeTypes } from "./nodes";import "./builder.css";import TeamBuilderToolbar from "./toolbar";import { MonacoEditor } from "../../monaco";-import { NodeEditor } from "./node-editor/node-editor";import debounce from "lodash.debounce";import TestDrawer from "./testdrawer";import { validationAPI, ValidationResponse } from "../api";import { ValidationErrors } from "./validationerrors";+import ComponentEditor from "./component-editor/component-editor";const { Sider, Content } = Layout;interface DragItemData {@@ -529,17 +529,35 @@ export const TeamBuilder: React.FC<TeamBuilderProps> = ({</Content></Layout>- <NodeEditor- node={nodes.find((n) => n.id === selectedNodeId) || null}- onUpdate={(updates) => {- if (selectedNodeId) {- console.log("updating node", selectedNodeId, updates);- updateNode(selectedNodeId, updates);- handleSave();- }- }}- onClose={() => setSelectedNode(null)}- />+ {selectedNodeId && (+ <Drawer+ title="Edit Component"+ placement="right"+ size="large"+ onClose={() => setSelectedNode(null)}+ open={!!selectedNodeId}+ className="component-editor-drawer"+ >+ {nodes.find((n) => n.id === selectedNodeId)?.data.component && (+ <ComponentEditor+ component={+ nodes.find((n) => n.id === selectedNodeId)!.data.component+ }+ onChange={(updatedComponent) => {+ console.log("builder updating component", updatedComponent);+ if (selectedNodeId) {+ updateNode(selectedNodeId, {+ component: updatedComponent,+ });+ handleSave();+ }+ }}+ onClose={() => setSelectedNode(null)}+ navigationDepth={true}+ />+ )}+ </Drawer>+ )}</Layout><DragOverlaydropAnimation={{diff --git a/python/packages/autogen-studio/frontend/src/components/views/team/builder/component-editor/component-editor.tsx b/python/packages/autogen-studio/frontend/src/components/views/team/builder/component-editor/component-editor.tsxnew file mode 100644index 000000000..445cc3959--- /dev/null+++ b/python/packages/autogen-studio/frontend/src/components/views/team/builder/component-editor/component-editor.tsx@@ -0,0 +1,302 @@+import React, { useState, useCallback, useRef } from "react";+import { Button, Breadcrumb } from "antd";+import { ChevronLeft, Code, FormInput } from "lucide-react";+import { Component, ComponentConfig } from "../../../../types/datamodel";+import {+ isTeamComponent,+ isAgentComponent,+ isModelComponent,+ isToolComponent,+ isTerminationComponent,+} from "../../../../types/guards";+import { AgentFields } from "./fields/agent-fields";+import { ModelFields } from "./fields/model-fields";+import { TeamFields } from "./fields/team-fields";+import { ToolFields } from "./fields/tool-fields";+import { TerminationFields } from "./fields/termination-fields";+import debounce from "lodash.debounce";+import { MonacoEditor } from "../../../monaco";++export interface EditPath {+ componentType: string;+ id: string;+ parentField: string;+}++export interface ComponentEditorProps {+ component: Component<ComponentConfig>;+ onChange: (updatedComponent: Component<ComponentConfig>) => void;+ onClose?: () => void;+ navigationDepth?: boolean;+}++export const ComponentEditor: React.FC<ComponentEditorProps> = ({+ component,+ onChange,+ onClose,+ navigationDepth = false,+}) => {+ const [editPath, setEditPath] = useState<EditPath[]>([]);+ const [workingCopy, setWorkingCopy] = useState<Component<ComponentConfig>>(+ Object.assign({}, component)+ );+ const [isJsonEditing, setIsJsonEditing] = useState(false);++ const editorRef = useRef(null);++ // Reset working copy when component changes+ React.useEffect(() => {+ setWorkingCopy(component);+ setEditPath([]);+ }, [component]);++ const getCurrentComponent = useCallback(+ (root: Component<ComponentConfig>) => {+ return editPath.reduce<Component<ComponentConfig> | null>(+ (current, path) => {+ if (!current) return null;++ const field = current.config[+ path.parentField as keyof typeof current.config+ ] as+ | Component<ComponentConfig>[]+ | Component<ComponentConfig>+ | undefined;++ if (Array.isArray(field)) {+ return (+ field.find(+ (item) =>+ item.label === path.id ||+ (item.config &&+ "name" in item.config &&+ item.config.name === path.id)+ ) || null+ );+ }++ return field || null;+ },+ root+ );+ },+ [editPath]+ );++ const updateComponentAtPath = useCallback(+ (+ root: Component<ComponentConfig>,+ path: EditPath[],+ updates: Partial<Component<ComponentConfig>>+ ): Component<ComponentConfig> => {+ if (path.length === 0) {+ return {+ ...root,+ ...updates,+ config: {+ ...root.config,+ ...(updates.config || {}),+ },+ };+ }++ const [currentPath, ...remainingPath] = path;+ const field =+ root.config[currentPath.parentField as keyof typeof root.config];++ const updateField = (fieldValue: any): any => {+ if (Array.isArray(fieldValue)) {+ return fieldValue.map((item) => {+ if (!("component_type" in item)) return item;+ if (+ item.label === currentPath.id ||+ ("name" in item.config && item.config.name === currentPath.id)+ ) {+ return updateComponentAtPath(item, remainingPath, updates);+ }+ return item;+ });+ }++ if (fieldValue && "component_type" in fieldValue) {+ return updateComponentAtPath(+ fieldValue as Component<ComponentConfig>,+ remainingPath,+ updates+ );+ }++ return fieldValue;+ };++ return {+ ...root,+ config: {+ ...root.config,+ [currentPath.parentField]: updateField(field),+ },+ };+ },+ []+ );++ const handleComponentUpdate = useCallback(+ (updates: Partial<Component<ComponentConfig>>) => {+ const updatedComponent = updateComponentAtPath(+ workingCopy,+ editPath,+ updates+ );+ console.log("updatedComponent", updatedComponent);+ setWorkingCopy(updatedComponent);+ // onChange(updatedComponent);+ },+ [workingCopy, editPath, updateComponentAtPath]+ );++ const handleNavigate = useCallback(+ (componentType: string, id: string, parentField: string) => {+ if (!navigationDepth) return;+ setEditPath((prev) => [...prev, { componentType, id, parentField }]);+ },+ [navigationDepth]+ );++ const handleNavigateBack = useCallback(() => {+ setEditPath((prev) => prev.slice(0, -1));+ }, []);++ const debouncedJsonUpdate = useCallback(+ debounce((value: string) => {+ try {+ const updatedComponent = JSON.parse(value);+ setWorkingCopy(updatedComponent);+ } catch (err) {+ console.error("Invalid JSON", err);+ }+ }, 500),+ []+ );++ const currentComponent = getCurrentComponent(workingCopy) || workingCopy;++ const renderFields = useCallback(() => {+ const commonProps = {+ component: currentComponent,+ onChange: handleComponentUpdate,+ };++ if (isTeamComponent(currentComponent)) {+ return (+ <TeamFields+ component={currentComponent}+ onChange={handleComponentUpdate}+ onNavigate={handleNavigate}+ />+ );+ }+ if (isAgentComponent(currentComponent)) {+ return (+ <AgentFields+ component={currentComponent}+ onChange={handleComponentUpdate}+ onNavigate={handleNavigate}+ />+ );+ }+ if (isModelComponent(currentComponent)) {+ return (+ <ModelFields+ component={currentComponent}+ onChange={handleComponentUpdate}+ />+ );+ }+ if (isToolComponent(currentComponent)) {+ return <ToolFields {...commonProps} />;+ }+ if (isTerminationComponent(currentComponent)) {+ return (+ <TerminationFields+ component={currentComponent}+ onChange={handleComponentUpdate}+ />+ );+ }++ return null;+ }, [currentComponent, handleComponentUpdate, handleNavigate]);++ const breadcrumbItems = React.useMemo(+ () => [+ { title: workingCopy.label || "Root" },+ ...editPath.map((path) => ({+ title: path.id,+ })),+ ],+ [workingCopy.label, editPath]+ );++ const handleSave = useCallback(() => {+ console.log("working copy", workingCopy.config);+ onChange(workingCopy);+ onClose?.();+ }, [workingCopy, onChange, onClose]);++ return (+ <div className="flex flex-col h-full">+ <div className="flex items-center gap-4 mb-6">+ {navigationDepth && editPath.length > 0 && (+ <Button+ onClick={handleNavigateBack}+ icon={<ChevronLeft className="w-4 h-4" />}+ type="text"+ />+ )}+ <div className="flex-1">+ <Breadcrumb items={breadcrumbItems} />+ </div>+ <Button+ onClick={() => setIsJsonEditing((prev) => !prev)}+ type="default"+ className="flex text-accent items-center gap-2 text-xs "+ >+ {isJsonEditing ? (+ <>+ <FormInput className="w-4 text-accent h-4 mr-1 inline-block" />+ Switch to Form Editor+ </>+ ) : (+ <>+ <Code className="w-4 text-accent h-4 mr-1 inline-block" />+ Switch to JSON Editor+ </>+ )}+ </Button>+ </div>+ {isJsonEditing ? (+ <div className="flex-1 overflow-y-auto">+ <MonacoEditor+ editorRef={editorRef}+ value={JSON.stringify(workingCopy, null, 2)}+ onChange={debouncedJsonUpdate}+ language="json"+ minimap={true}+ />+ </div>+ ) : (+ <div className="flex-1 overflow-y-auto">{renderFields()}</div>+ )}+ {onClose && (+ <div className="flex justify-end gap-2 mt-6 pt-4 border-t border-secondary">+ <Button onClick={onClose}>Cancel</Button>+ <Button type="primary" onClick={handleSave}>+ Save Changes+ </Button>+ </div>+ )}+ </div>+ );+};++export default ComponentEditor;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/component-editor/detailgroup.tsxsimilarity index 100%rename from python/packages/autogen-studio/frontend/src/components/views/team/builder/node-editor/detailgroup.tsxrename to python/packages/autogen-studio/frontend/src/components/views/team/builder/component-editor/detailgroup.tsxdiff --git a/python/packages/autogen-studio/frontend/src/components/views/team/builder/component-editor/fields/agent-fields.tsx b/python/packages/autogen-studio/frontend/src/components/views/team/builder/component-editor/fields/agent-fields.tsxnew file mode 100644index 000000000..4034a88ea--- /dev/null+++ b/python/packages/autogen-studio/frontend/src/components/views/team/builder/component-editor/fields/agent-fields.tsx@@ -0,0 +1,324 @@+import React, { useCallback } from "react";+import { Input, Switch, Button, Tooltip } from "antd";+import { Edit, HelpCircle, Trash2 } from "lucide-react";+import {+ Component,+ ComponentConfig,+ AgentConfig,+} from "../../../../../types/datamodel";+import {+ isAssistantAgent,+ isUserProxyAgent,+ isWebSurferAgent,+} from "../../../../../types/guards";+import DetailGroup from "../detailgroup";++const { TextArea } = Input;++interface AgentFieldsProps {+ component: Component<AgentConfig>;+ onChange: (updates: Partial<Component<ComponentConfig>>) => void;+ onNavigate?: (componentType: string, id: string, parentField: string) => void;+}++const InputWithTooltip: React.FC<{+ label: string;+ tooltip: string;+ required?: boolean;+ children: React.ReactNode;+}> = ({ label, tooltip, required, children }) => (+ <label className="block">+ <div className="flex items-center gap-2 mb-1">+ <span className="text-sm font-medium text-primary">+ {label} {required && <span className="text-red-500">*</span>}+ </span>+ <Tooltip title={tooltip}>+ <HelpCircle className="w-4 h-4 text-secondary" />+ </Tooltip>+ </div>+ {children}+ </label>+);++export const AgentFields: React.FC<AgentFieldsProps> = ({+ component,+ onChange,+ onNavigate,+}) => {+ if (!component) return null;++ const handleComponentUpdate = useCallback(+ (updates: Partial<Component<ComponentConfig>>) => {+ onChange({+ ...component,+ ...updates,+ config: {+ ...component.config,+ ...(updates.config || {}),+ },+ });+ },+ [component, onChange]+ );++ const handleConfigUpdate = useCallback(+ (field: string, value: unknown) => {+ handleComponentUpdate({+ config: {+ ...component.config,+ [field]: value,+ },+ });+ },+ [component, handleComponentUpdate]+ );++ const handleRemoveTool = useCallback(+ (toolIndex: number) => {+ if (!isAssistantAgent(component)) return;+ const newTools = [...(component.config.tools || [])];+ newTools.splice(toolIndex, 1);+ handleConfigUpdate("tools", newTools);+ },+ [component, handleConfigUpdate]+ );++ const renderNestedComponents = () => {+ if (isAssistantAgent(component)) {+ return (+ <div className="space-y-4">+ {component.config.model_client && (+ <div className="space-y-2">+ <h3 className="text-sm font-medium text-primary">Model Client</h3>+ <div className="bg-secondary p-4 rounded-md">+ <div className="flex items-center justify-between">+ <span className="text-sm">+ {component.config.model_client.config.model}+ </span>+ {onNavigate && (+ <Button+ type="text"+ icon={<Edit className="w-4 h-4" />}+ onClick={() => {+ console.log("model clicked");+ onNavigate(+ "model",+ component.config.model_client?.label || "",+ "model_client"+ );+ }}+ />+ )}+ </div>+ </div>+ </div>+ )}++ {component.config.tools && component.config.tools.length > 0 && (+ <div className="space-y-2">+ <h3 className="text-sm font-medium text-primary">Tools</h3>+ <div className="space-y-2">+ {component.config.tools.map((tool, index) => (+ <div key={tool.label} className="bg-secondary p-4 rounded-md">+ <div className="flex items-center justify-between">+ <span className="text-sm">+ {tool.label || tool.config.name}+ </span>+ <div className="flex items-center gap-2">+ {onNavigate && (+ <Button+ type="text"+ icon={<Edit className="w-4 h-4" />}+ onClick={() =>+ onNavigate(+ "tool",+ tool.label || tool.config.name || "",+ "tools"+ )+ }+ />+ )}+ <Button+ type="text"+ danger+ icon={<Trash2 className="w-4 h-4" />}+ onClick={() => handleRemoveTool(index)}+ />+ </div>+ </div>+ </div>+ ))}+ </div>+ </div>+ )}+ </div>+ );+ }++ if (isWebSurferAgent(component)) {+ return (+ <div className="space-y-4">+ {component.config.model_client && (+ <div className="space-y-2">+ <h3 className="text-sm font-medium text-primary">Model Client</h3>+ <div className="bg-secondary p-4 rounded-md">+ <div className="flex items-center justify-between">+ <span className="text-sm">+ {component.config.model_client.config.model}+ </span>+ {onNavigate && (+ <Button+ type="text"+ icon={<Edit className="w-4 h-4" />}+ onClick={() =>+ onNavigate(+ "model",+ component.config.model_client?.label || "",+ "model_client"+ )+ }+ />+ )}+ </div>+ </div>+ </div>+ )}+ </div>+ );+ }++ return (+ <div className="text-sm text-gray-500 text-center">+ No nested components+ </div>+ );+ };++ return (+ <div className="space-y-6">+ <DetailGroup title="Component Details">+ <div className="space-y-4">+ <label className="block">+ <span className="text-sm font-medium text-primary">Name</span>+ <Input+ value={component.label || ""}+ onChange={(e) => handleComponentUpdate({ label: e.target.value })}+ placeholder="Component name"+ className="mt-1"+ />+ </label>++ <label className="block">+ <span className="text-sm font-medium text-primary">+ Description+ </span>+ <TextArea+ value={component.description || ""}+ onChange={(e) =>+ handleComponentUpdate({ description: e.target.value })+ }+ placeholder="Component description"+ rows={4}+ className="mt-1"+ />+ </label>+ </div>+ </DetailGroup>++ <DetailGroup title="Nested Components">+ {renderNestedComponents()}+ </DetailGroup>++ <DetailGroup title="Configuration">+ <div className="space-y-4">+ {isAssistantAgent(component) && (+ <>+ <InputWithTooltip+ label="Name"+ tooltip="Name of the assistant agent"+ required+ >+ <Input+ value={component.config.name}+ onChange={(e) => handleConfigUpdate("name", e.target.value)}+ />+ </InputWithTooltip>++ <InputWithTooltip+ label="System Message"+ tooltip="System message for the agent"+ >+ <TextArea+ rows={4}+ value={component.config.system_message}+ onChange={(e) =>+ handleConfigUpdate("system_message", e.target.value)+ }+ />+ </InputWithTooltip>++ <div className="flex items-center justify-between">+ <span className="text-sm font-medium text-primary">+ Reflect on Tool Use+ </span>+ <Switch+ checked={component.config.reflect_on_tool_use}+ onChange={(checked) =>+ handleConfigUpdate("reflect_on_tool_use", checked)+ }+ />+ </div>++ <InputWithTooltip+ label="Tool Call Summary Format"+ tooltip="Format for tool call summaries"+ >+ <Input+ value={component.config.tool_call_summary_format}+ onChange={(e) =>+ handleConfigUpdate(+ "tool_call_summary_format",+ e.target.value+ )+ }+ />+ </InputWithTooltip>+ </>+ )}++ {isUserProxyAgent(component) && (+ <InputWithTooltip+ label="Name"+ tooltip="Name of the user proxy agent"+ required+ >+ <Input+ value={component.config.name}+ onChange={(e) => handleConfigUpdate("name", e.target.value)}+ />+ </InputWithTooltip>+ )}++ {isWebSurferAgent(component) && (+ // Web surfer specific configuration fields...+ <>+ <InputWithTooltip+ label="Name"+ tooltip="Name of the web surfer agent"+ required+ >+ <Input+ value={component.config.name}+ onChange={(e) => handleConfigUpdate("name", e.target.value)}+ />+ </InputWithTooltip>+ {/* Add other web surfer fields here */}+ </>+ )}+ </div>+ </DetailGroup>+ </div>+ );+};++export default React.memo(AgentFields);diff --git a/python/packages/autogen-studio/frontend/src/components/views/team/builder/component-editor/fields/fields.tsx b/python/packages/autogen-studio/frontend/src/components/views/team/builder/component-editor/fields/fields.tsxnew file mode 100644index 000000000..3edd2abad--- /dev/null+++ b/python/packages/autogen-studio/frontend/src/components/views/team/builder/component-editor/fields/fields.tsx@@ -0,0 +1,290 @@+import React from "react";+import { Button, Form, Input } from "antd";++import {+ Component,+ ComponentConfig,+ FunctionToolConfig,+} from "../../../../../types/datamodel";+import {+ isTeamComponent,+ isAgentComponent,+ isModelComponent,+ isToolComponent,+ isTerminationComponent,+} from "../../../../../types/guards";+import DetailGroup from "../detailgroup";+import { TeamFields } from "./team-fields";+import { AgentFields } from "./agent-fields";+import { ModelFields } from "./model-fields";+import { ToolFields } from "./tool-fields";+import { TerminationFields } from "./termination-fields";+import { Edit, MinusCircle, PlusCircle } from "lucide-react";+import { EditPath } from "../node-editor";++const { TextArea } = Input;++export interface NodeEditorFieldsProps {+ component: Component<ComponentConfig>;+ onNavigate: (componentType: string, id: string, parentField: string) => void;+ workingCopy: Component<ComponentConfig> | null;+ setWorkingCopy: (component: Component<ComponentConfig> | null) => void;+ editPath: EditPath[];+ updateComponentAtPath: (+ root: Component<ComponentConfig>,+ path: EditPath[],+ updates: Partial<Component<ComponentConfig>>+ ) => Component<ComponentConfig>;+ getCurrentComponent: (+ root: Component<ComponentConfig>+ ) => Component<ComponentConfig> | null;+}++const NodeEditorFields: React.FC<NodeEditorFieldsProps> = ({+ component,+ onNavigate,+ workingCopy,+ setWorkingCopy,+ editPath,+ updateComponentAtPath,+ getCurrentComponent,+}) => {+ let specificFields = null;++ if (isTeamComponent(component)) {+ specificFields = (+ <DetailGroup title="Configuration">+ <TeamFields+ component={component}+ onNavigate={onNavigate}+ workingCopy={workingCopy}+ setWorkingCopy={setWorkingCopy}+ editPath={editPath}+ updateComponentAtPath={updateComponentAtPath}+ getCurrentComponent={getCurrentComponent}+ />+ </DetailGroup>+ );+ } else if (isAgentComponent(component)) {+ specificFields = (+ <DetailGroup title="Configuration">+ <AgentFields+ component={component}+ onNavigate={onNavigate}+ workingCopy={workingCopy}+ setWorkingCopy={setWorkingCopy}+ editPath={editPath}+ updateComponentAtPath={updateComponentAtPath}+ getCurrentComponent={getCurrentComponent}+ />+ </DetailGroup>+ );+ } else if (isModelComponent(component)) {+ specificFields = (+ <DetailGroup title="Configuration">+ <ModelFields component={component} />+ </DetailGroup>+ );+ } else if (isToolComponent(component)) {+ specificFields = (+ <DetailGroup title="Configuration">+ <ToolFields+ component={component}+ workingCopy={workingCopy}+ setWorkingCopy={setWorkingCopy}+ editPath={editPath}+ updateComponentAtPath={updateComponentAtPath}+ getCurrentComponent={getCurrentComponent}+ />+ </DetailGroup>+ );+ } else if (isTerminationComponent(component)) {+ specificFields = (+ <DetailGroup title="Configuration">+ <TerminationFields+ component={component}+ onNavigate={onNavigate}+ workingCopy={workingCopy}+ setWorkingCopy={setWorkingCopy}+ editPath={editPath}+ updateComponentAtPath={updateComponentAtPath}+ getCurrentComponent={getCurrentComponent}+ />+ </DetailGroup>+ );+ }++ return (+ <>+ <DetailGroup title="Component Details">+ <CommonFields />+ </DetailGroup>+ {specificFields}+ </>+ );+};++export default NodeEditorFields;++// // fields/common-fields.tsx++export const CommonFields: React.FC = () => {+ return (+ <>+ <Form.Item label="Label" name="label">+ <Input />+ </Form.Item>+ <Form.Item label="Description" name="description">+ <TextArea rows={4} />+ </Form.Item>+ </>+ );+};++interface NestedComponentButtonProps {+ label: string;+ component: Component<ComponentConfig> | Component<ComponentConfig>[];+ parentField: string;+ onNavigate: (componentType: string, id: string, parentField: string) => void;+ workingCopy?: Component<ComponentConfig> | null;+ setWorkingCopy?: (component: Component<ComponentConfig> | null) => void;+ editPath?: any[];+ updateComponentAtPath?: any;+ getCurrentComponent?: any;+}++export const NestedComponentButton: React.FC<NestedComponentButtonProps> = ({+ label,+ component,+ parentField,+ onNavigate,+ workingCopy,+ setWorkingCopy,+ editPath,+ updateComponentAtPath,+ getCurrentComponent,+}) => {+ 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>+ {parentField === "tools" && (+ <Button+ type="dashed"+ size="small"+ onClick={() => {+ const blankTool: Component<FunctionToolConfig> = {+ provider: "autogen_core.tools.FunctionTool",+ component_type: "tool",+ version: 1,+ component_version: 1,+ description:+ "Create custom tools by wrapping standard Python functions.",+ label: "New Tool",+ config: {+ source_code: "def new_function():\n pass",+ name: "new_function",+ description: "Description of the new function",+ global_imports: [],+ has_cancellation_support: false,+ },+ };++ if (+ workingCopy &&+ setWorkingCopy &&+ updateComponentAtPath &&+ getCurrentComponent &&+ editPath+ ) {+ const currentTools =+ component as Component<ComponentConfig>[];+ const updatedTools = [...currentTools, blankTool];+ const updatedCopy = updateComponentAtPath(+ workingCopy,+ editPath,+ {+ config: {+ ...getCurrentComponent(workingCopy)?.config,+ tools: updatedTools,+ },+ }+ );+ setWorkingCopy(updatedCopy);+ }+ }}+ icon={<PlusCircle className="w-4 h-4" />}+ >+ Add Tool+ </Button>+ )}+ </div>+ {component.map((item, index) => (+ <div key={item.label} className="flex items-center gap-2">+ <Button+ 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>+ {parentField === "tools" && (+ <Button+ type="text"+ danger+ icon={<MinusCircle className="w-4 h-4" />}+ onClick={() => {+ if (+ workingCopy &&+ setWorkingCopy &&+ updateComponentAtPath &&+ getCurrentComponent &&+ editPath+ ) {+ const currentTools =+ component as Component<ComponentConfig>[];+ const updatedTools = currentTools.filter(+ (_, idx) => idx !== index+ );+ const updatedCopy = updateComponentAtPath(+ workingCopy,+ editPath,+ {+ config: {+ ...getCurrentComponent(workingCopy)?.config,+ tools: updatedTools,+ },+ }+ );+ setWorkingCopy(updatedCopy);+ }+ }}+ />+ )}+ </div>+ ))}+ </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;+};diff --git a/python/packages/autogen-studio/frontend/src/components/views/team/builder/component-editor/fields/model-fields.tsx b/python/packages/autogen-studio/frontend/src/components/views/team/builder/component-editor/fields/model-fields.tsxnew file mode 100644index 000000000..5af067cfc--- /dev/null+++ b/python/packages/autogen-studio/frontend/src/components/views/team/builder/component-editor/fields/model-fields.tsx@@ -0,0 +1,350 @@+import React, { useCallback } from "react";+import { Input, InputNumber, Select, Tooltip } from "antd";+import { HelpCircle } from "lucide-react";+import {+ Component,+ ComponentConfig,+ ModelConfig,+} from "../../../../../types/datamodel";+import { isOpenAIModel, isAzureOpenAIModel } from "../../../../../types/guards";+import DetailGroup from "../detailgroup";+import TextArea from "antd/es/input/TextArea";+// import DetailGroup from "./detail-group";++interface ModelFieldsProps {+ component: Component<ModelConfig>;+ onChange: (updates: Partial<Component<ComponentConfig>>) => void;+}++const InputWithTooltip: React.FC<{+ label: string;+ tooltip: string;+ children: React.ReactNode;+}> = ({ label, tooltip, children }) => (+ <label className="block">+ <div className="flex items-center gap-2 mb-1">+ <span className="text-sm font-medium text-primary">{label}</span>+ <Tooltip title={tooltip}>+ <HelpCircle className="w-4 h-4 text-secondary" />+ </Tooltip>+ </div>+ {children}+ </label>+);++export const ModelFields: React.FC<ModelFieldsProps> = ({+ component,+ onChange,+}) => {+ if (!isOpenAIModel(component) && !isAzureOpenAIModel(component)) return null;++ const handleComponentUpdate = useCallback(+ (updates: Partial<Component<ComponentConfig>>) => {+ onChange({+ ...component,+ ...updates,+ config: {+ ...component.config,+ ...(updates.config || {}),+ },+ });+ },+ [component, onChange]+ );++ const handleConfigUpdate = useCallback(+ (field: string, value: unknown) => {+ handleComponentUpdate({+ config: {+ ...component.config,+ [field]: value,+ },+ });+ },+ [component, handleComponentUpdate]+ );++ // Common arguments fields shared between OpenAI and Azure OpenAI models+ const ArgumentsFields = () => (+ <div className="space-y-4">+ <InputWithTooltip+ label="Temperature"+ tooltip="Controls randomness in the model's output. Higher values (e.g., 0.8) make output more random, lower values (e.g., 0.2) make it more focused."+ >+ <InputNumber+ min={0}+ max={2}+ step={0.1}+ value={component.config.temperature}+ onChange={(value) => handleConfigUpdate("temperature", value)}+ className="w-full"+ />+ </InputWithTooltip>++ <InputWithTooltip+ label="Max Tokens"+ tooltip="Maximum length of the model's output in tokens"+ >+ <InputNumber+ min={1}+ value={component.config.max_tokens}+ onChange={(value) => handleConfigUpdate("max_tokens", value)}+ className="w-full"+ />+ </InputWithTooltip>++ <InputWithTooltip+ label="Top P"+ tooltip="Controls diversity via nucleus sampling. Lower values (e.g., 0.1) make output more focused, higher values (e.g., 0.9) make it more diverse."+ >+ <InputNumber+ min={0}+ max={1}+ step={0.1}+ value={component.config.top_p}+ onChange={(value) => handleConfigUpdate("top_p", value)}+ className="w-full"+ />+ </InputWithTooltip>++ <InputWithTooltip+ label="Frequency Penalty"+ tooltip="Decreases the model's likelihood to repeat the same information. Values range from -2.0 to 2.0."+ >+ <InputNumber+ min={-2}+ max={2}+ step={0.1}+ value={component.config.frequency_penalty}+ onChange={(value) => handleConfigUpdate("frequency_penalty", value)}+ className="w-full"+ />+ </InputWithTooltip>++ <InputWithTooltip+ label="Presence Penalty"+ tooltip="Increases the model's likelihood to talk about new topics. Values range from -2.0 to 2.0."+ >+ <InputNumber+ min={-2}+ max={2}+ step={0.1}+ value={component.config.presence_penalty}+ onChange={(value) => handleConfigUpdate("presence_penalty", value)}+ className="w-full"+ />+ </InputWithTooltip>++ <InputWithTooltip+ label="Stop Sequences"+ tooltip="Sequences where the model will stop generating further tokens"+ >+ <Select+ mode="tags"+ value={component.config.stop as string[]}+ onChange={(value) => handleConfigUpdate("stop", value)}+ placeholder="Enter stop sequences"+ className="w-full"+ />+ </InputWithTooltip>+ </div>+ );++ if (isOpenAIModel(component)) {+ return (+ <div className="space-y-6">+ <DetailGroup title="Component Details">+ <div className="space-y-4">+ <label className="block">+ <span className="text-sm font-medium text-primary">Name</span>+ <Input+ value={component.label || ""}+ onChange={(e) =>+ handleComponentUpdate({ label: e.target.value })+ }+ placeholder="Team name"+ className="mt-1"+ />+ </label>++ <label className="block">+ <span className="text-sm font-medium text-primary">+ Description+ </span>+ <TextArea+ value={component.description || ""}+ onChange={(e) =>+ handleComponentUpdate({ description: e.target.value })+ }+ placeholder="Team description"+ rows={4}+ className="mt-1"+ />+ </label>+ </div>+ </DetailGroup>++ <DetailGroup title="Model Configuration">+ <div className="space-y-4">+ <InputWithTooltip+ label="Model"+ tooltip="The name of the OpenAI model to use (e.g., gpt-4, gpt-3.5-turbo)"+ >+ <Input+ value={component.config.model}+ onChange={(e) => handleConfigUpdate("model", e.target.value)}+ required+ />+ </InputWithTooltip>++ <InputWithTooltip label="API Key" tooltip="Your OpenAI API key">+ <Input.Password+ value={component.config.api_key}+ onChange={(e) => handleConfigUpdate("api_key", e.target.value)}+ />+ </InputWithTooltip>++ <InputWithTooltip+ label="Organization"+ tooltip="Optional: Your OpenAI organization ID"+ >+ <Input+ value={component.config.organization}+ onChange={(e) =>+ handleConfigUpdate("organization", e.target.value)+ }+ />+ </InputWithTooltip>++ <InputWithTooltip+ label="Base URL"+ tooltip="Optional: Custom base URL for API requests"+ >+ <Input+ value={component.config.base_url}+ onChange={(e) => handleConfigUpdate("base_url", e.target.value)}+ />+ </InputWithTooltip>++ <InputWithTooltip+ label="Timeout"+ tooltip="Request timeout in seconds"+ >+ <InputNumber+ min={1}+ value={component.config.timeout}+ onChange={(value) => handleConfigUpdate("timeout", value)}+ className="w-full"+ />+ </InputWithTooltip>++ <InputWithTooltip+ label="Max Retries"+ tooltip="Maximum number of retry attempts for failed requests"+ >+ <InputNumber+ min={0}+ value={component.config.max_retries}+ onChange={(value) => handleConfigUpdate("max_retries", value)}+ className="w-full"+ />+ </InputWithTooltip>+ </div>+ </DetailGroup>++ <DetailGroup title="Model Parameters">+ <ArgumentsFields />+ </DetailGroup>+ </div>+ );+ }++ if (isAzureOpenAIModel(component)) {+ return (+ <div className="space-y-6">+ <DetailGroup title="Azure Configuration">+ <div className="space-y-4">+ <InputWithTooltip+ label="Model"+ tooltip="The name of the Azure OpenAI model deployment"+ >+ <Input+ value={component.config.model}+ onChange={(e) => handleConfigUpdate("model", e.target.value)}+ required+ />+ </InputWithTooltip>++ <InputWithTooltip+ label="Azure Endpoint"+ tooltip="Your Azure OpenAI service endpoint URL"+ >+ <Input+ value={component.config.azure_endpoint}+ onChange={(e) =>+ handleConfigUpdate("azure_endpoint", e.target.value)+ }+ required+ />+ </InputWithTooltip>++ <InputWithTooltip+ label="API Key"+ tooltip="Your Azure OpenAI API key"+ >+ <Input.Password+ value={component.config.api_key}+ onChange={(e) => handleConfigUpdate("api_key", e.target.value)}+ />+ </InputWithTooltip>++ <InputWithTooltip+ label="Azure Deployment"+ tooltip="The name of your Azure OpenAI model deployment"+ >+ <Input+ value={component.config.azure_deployment}+ onChange={(e) =>+ handleConfigUpdate("azure_deployment", e.target.value)+ }+ />+ </InputWithTooltip>++ <InputWithTooltip+ label="API Version"+ tooltip="Azure OpenAI API version (e.g., 2023-05-15)"+ >+ <Input+ value={component.config.api_version}+ onChange={(e) =>+ handleConfigUpdate("api_version", e.target.value)+ }+ required+ />+ </InputWithTooltip>++ <InputWithTooltip+ label="Azure AD Token"+ tooltip="Optional: Azure Active Directory token for authentication"+ >+ <Input.Password+ value={component.config.azure_ad_token}+ onChange={(e) =>+ handleConfigUpdate("azure_ad_token", e.target.value)+ }+ />+ </InputWithTooltip>+ </div>+ </DetailGroup>++ <DetailGroup title="Model Parameters">+ <ArgumentsFields />+ </DetailGroup>+ </div>+ );+ }++ return null;+};++export default React.memo(ModelFields);diff --git a/python/packages/autogen-studio/frontend/src/components/views/team/builder/component-editor/fields/team-fields.tsx b/python/packages/autogen-studio/frontend/src/components/views/team/builder/component-editor/fields/team-fields.tsxnew file mode 100644index 000000000..9e02c9249--- /dev/null+++ b/python/packages/autogen-studio/frontend/src/components/views/team/builder/component-editor/fields/team-fields.tsx@@ -0,0 +1,185 @@+import React, { useCallback } from "react";+import { Input, Button } from "antd";+import { Edit, Timer } from "lucide-react";+import {+ Component,+ TeamConfig,+ ComponentConfig,+ RoundRobinGroupChatConfig,+ SelectorGroupChatConfig,+} from "../../../../../types/datamodel";+import { isSelectorTeam, isRoundRobinTeam } from "../../../../../types/guards";+import DetailGroup from "../detailgroup";++const { TextArea } = Input;++interface TeamFieldsProps {+ component: Component<TeamConfig>;+ onChange: (updates: Partial<Component<ComponentConfig>>) => void;+ onNavigate?: (componentType: string, id: string, parentField: string) => void;+}++export const TeamFields: React.FC<TeamFieldsProps> = ({+ component,+ onChange,+ onNavigate,+}) => {+ if (!isSelectorTeam(component) && !isRoundRobinTeam(component)) return null;++ const handleComponentUpdate = useCallback(+ (updates: Partial<Component<ComponentConfig>>) => {+ onChange({+ ...component,+ ...updates,+ config: {+ ...component.config,+ ...(updates.config || {}),+ },+ });+ },+ [component, onChange]+ );++ const handleConfigUpdate = useCallback(+ (field: string, value: unknown) => {+ if (isSelectorTeam(component)) {+ handleComponentUpdate({+ config: {+ ...component.config,+ [field]: value,+ } as SelectorGroupChatConfig,+ });+ } else if (isRoundRobinTeam(component)) {+ handleComponentUpdate({+ config: {+ ...component.config,+ [field]: value,+ } as RoundRobinGroupChatConfig,+ });+ }+ },+ [component, handleComponentUpdate]+ );++ return (+ <div className=" ">+ <DetailGroup title="Component Details">+ <div className="space-y-4">+ <label className="block">+ <span className="text-sm font-medium text-primary">Name</span>+ <Input+ value={component.label || ""}+ onChange={(e) => handleComponentUpdate({ label: e.target.value })}+ placeholder="Team name"+ className="mt-1"+ />+ </label>++ <label className="block">+ <span className="text-sm font-medium text-primary">+ Description+ </span>+ <TextArea+ value={component.description || ""}+ onChange={(e) =>+ handleComponentUpdate({ description: e.target.value })+ }+ placeholder="Team description"+ rows={4}+ className="mt-1"+ />+ </label>+ </div>+ </DetailGroup>++ <DetailGroup title="Configuration">+ {isSelectorTeam(component) && (+ <div className="space-y-4">+ <label className="block">+ <span className="text-sm font-medium text-primary">+ Selector Prompt+ </span>+ <TextArea+ value={component.config.selector_prompt || ""}+ onChange={(e) =>+ handleConfigUpdate("selector_prompt", e.target.value)+ }+ placeholder="Prompt for the selector"+ rows={4}+ className="mt-1"+ />+ </label>++ <div className="space-y-2">+ <h3 className="text-sm font-medium text-primary">Model</h3>+ <div className="bg-secondary p-4 rounded-md">+ {component.config.model_client ? (+ <div className="flex items-center justify-between">+ <span className="text-sm">+ {component.config.model_client.config.model}+ </span>+ {onNavigate && (+ <Button+ type="text"+ icon={<Edit className="w-4 h-4" />}+ onClick={() =>+ onNavigate(+ "model",+ component.config.model_client?.label || "",+ "model_client"+ )+ }+ />+ )}+ </div>+ ) : (+ <div className="text-sm text-secondary text-center">+ No model configured+ </div>+ )}+ </div>+ </div>+ </div>+ )}++ <div className="space-y-2 mt-4">+ <h3 className="text-sm font-medium text-primary">+ Termination Condition+ </h3>+ <div className="bg-secondary p-4 rounded-md">+ {component.config.termination_condition ? (+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2">+ <Timer className="w-4 h-4 text-secondary" />+ <span className="text-sm">+ {component.config.termination_condition.label ||+ component.config.termination_condition.component_type}+ </span>+ </div>+ {onNavigate && (+ <Button+ type="text"+ icon={<Edit className="w-4 h-4" />}+ onClick={() =>+ onNavigate(+ "termination",+ component.config.termination_condition?.label || "",+ "termination_condition"+ )+ }+ />+ )}+ </div>+ ) : (+ <div className="text-sm text-secondary text-center">+ No termination condition configured+ </div>+ )}+ </div>+ </div>+ </DetailGroup>+ </div>+ );+};++export default React.memo(TeamFields);diff --git a/python/packages/autogen-studio/frontend/src/components/views/team/builder/component-editor/fields/termination-fields.tsx b/python/packages/autogen-studio/frontend/src/components/views/team/builder/component-editor/fields/termination-fields.tsxnew file mode 100644index 000000000..c8f48bc61--- /dev/null+++ b/python/packages/autogen-studio/frontend/src/components/views/team/builder/component-editor/fields/termination-fields.tsx@@ -0,0 +1,242 @@+import React, { useCallback, useState } from "react";+import { Input, InputNumber, Button, Select, Tooltip } from "antd";+import { PlusCircle, MinusCircle, Edit, HelpCircle } from "lucide-react";+import {+ Component,+ ComponentConfig,+ TerminationConfig,+} from "../../../../../types/datamodel";+import {+ isOrTermination,+ isMaxMessageTermination,+ isTextMentionTermination,+} from "../../../../../types/guards";+import { PROVIDERS } from "../../../../../types/guards";+import DetailGroup from "../detailgroup";++interface TerminationFieldsProps {+ component: Component<TerminationConfig>;+ onChange: (updates: Partial<Component<ComponentConfig>>) => void;+ onNavigate?: (componentType: string, id: string, parentField: string) => void;+}++const TERMINATION_TYPES = {+ MAX_MESSAGE: {+ label: "Max Messages",+ provider: PROVIDERS.MAX_MESSAGE,+ defaultConfig: {+ max_messages: 10,+ include_agent_event: false,+ },+ },+ TEXT_MENTION: {+ label: "Text Mention",+ provider: PROVIDERS.TEXT_MENTION,+ defaultConfig: {+ text: "TERMINATE",+ },+ },+};++const InputWithTooltip: React.FC<{+ label: string;+ tooltip: string;+ children: React.ReactNode;+}> = ({ label, tooltip, children }) => (+ <label className="block">+ <div className="flex items-center gap-2 mb-1">+ <span className="text-sm font-medium text-gray-700">{label}</span>+ <Tooltip title={tooltip}>+ <HelpCircle className="w-4 h-4 text-gray-400" />+ </Tooltip>+ </div>+ {children}+ </label>+);++export const TerminationFields: React.FC<TerminationFieldsProps> = ({+ component,+ onChange,+ onNavigate,+}) => {+ const [showAddCondition, setShowAddCondition] = useState(false);+ const [selectedConditionType, setSelectedConditionType] =+ useState<string>("");++ if (!component) return null;++ const handleComponentUpdate = useCallback(+ (updates: Partial<Component<ComponentConfig>>) => {+ onChange({+ ...component,+ ...updates,+ config: {+ ...component.config,+ ...(updates.config || {}),+ },+ });+ },+ [component, onChange]+ );++ const createNewCondition = (type: string) => {+ const template = TERMINATION_TYPES[type as keyof typeof TERMINATION_TYPES];+ return {+ provider: template.provider,+ component_type: "termination",+ version: 1,+ component_version: 1,+ description: `${template.label} termination condition`,+ label: template.label,+ config: template.defaultConfig,+ };+ };++ const handleAddCondition = () => {+ if (!selectedConditionType || !isOrTermination(component)) return;++ const newCondition = createNewCondition(selectedConditionType);+ const currentConditions = component.config.conditions || [];++ handleComponentUpdate({+ config: {+ conditions: [...currentConditions, newCondition],+ },+ });++ setShowAddCondition(false);+ setSelectedConditionType("");+ };++ const handleRemoveCondition = (index: number) => {+ if (!isOrTermination(component)) return;++ const currentConditions = [...component.config.conditions];+ currentConditions.splice(index, 1);++ handleComponentUpdate({+ config: {+ conditions: currentConditions,+ },+ });+ };++ if (isOrTermination(component)) {+ return (+ <DetailGroup title="Termination Conditions">+ <div className="space-y-4">+ <div className="flex justify-between items-center">+ <Button+ type="dashed"+ onClick={() => setShowAddCondition(true)}+ icon={<PlusCircle className="w-4 h-4" />}+ className="w-full"+ >+ Add Condition+ </Button>+ </div>++ {showAddCondition && (+ <div className="border rounded p-4 space-y-4">+ <InputWithTooltip+ label="Condition Type"+ tooltip="Select the type of termination condition to add"+ >+ <Select+ value={selectedConditionType}+ onChange={setSelectedConditionType}+ className="w-full"+ >+ {Object.entries(TERMINATION_TYPES).map(([key, value]) => (+ <Select.Option key={key} value={key}>+ {value.label}+ </Select.Option>+ ))}+ </Select>+ </InputWithTooltip>+ <Button+ onClick={handleAddCondition}+ disabled={!selectedConditionType}+ className="w-full"+ >+ Add+ </Button>+ </div>+ )}++ <div className="space-y-2">+ {component.config.conditions?.map((condition, index) => (+ <div key={index} className="flex items-center gap-2">+ <Button+ onClick={() =>+ onNavigate?.(+ condition.component_type,+ condition.label || "",+ "conditions"+ )+ }+ className="w-full flex justify-between items-center"+ >+ <span>{condition.label || `Condition ${index + 1}`}</span>+ <Edit className="w-4 h-4" />+ </Button>+ <Button+ type="text"+ danger+ icon={<MinusCircle className="w-4 h-4" />}+ onClick={() => handleRemoveCondition(index)}+ />+ </div>+ ))}+ </div>+ </div>+ </DetailGroup>+ );+ }++ if (isMaxMessageTermination(component)) {+ return (+ <DetailGroup title="Max Messages Configuration">+ <InputWithTooltip+ label="Max Messages"+ tooltip="Maximum number of messages before termination"+ >+ <InputNumber+ min={1}+ value={component.config.max_messages}+ onChange={(value) =>+ handleComponentUpdate({+ config: { max_messages: value },+ })+ }+ className="w-full"+ />+ </InputWithTooltip>+ </DetailGroup>+ );+ }++ if (isTextMentionTermination(component)) {+ return (+ <DetailGroup title="Text Mention Configuration">+ <InputWithTooltip+ label="Termination Text"+ tooltip="Text that triggers termination when mentioned"+ >+ <Input+ value={component.config.text}+ onChange={(e) =>+ handleComponentUpdate({+ config: { text: e.target.value },+ })+ }+ />+ </InputWithTooltip>+ </DetailGroup>+ );+ }++ return null;+};++export default React.memo(TerminationFields);diff --git a/python/packages/autogen-studio/frontend/src/components/views/team/builder/component-editor/fields/tool-fields.tsx b/python/packages/autogen-studio/frontend/src/components/views/team/builder/component-editor/fields/tool-fields.tsxnew file mode 100644index 000000000..00013b752--- /dev/null+++ b/python/packages/autogen-studio/frontend/src/components/views/team/builder/component-editor/fields/tool-fields.tsx@@ -0,0 +1,292 @@+import React, { useCallback, useRef, useState } from "react";+import { Input, Switch, Select, Button, Space } from "antd";+import { PlusCircle, MinusCircle } from "lucide-react";+import {+ Component,+ ComponentConfig,+ Import,+} from "../../../../../types/datamodel";+import { isFunctionTool } from "../../../../../types/guards";+import { MonacoEditor } from "../../../../monaco";+import DetailGroup from "../detailgroup";++const { TextArea } = Input;+const { Option } = Select;++interface ToolFieldsProps {+ component: Component<ComponentConfig>;+ onChange: (updates: Partial<Component<ComponentConfig>>) => void;+}++interface ImportState {+ module: string;+ imports: string;+}++export const ToolFields: React.FC<ToolFieldsProps> = ({+ component,+ onChange,+}) => {+ if (!isFunctionTool(component)) return null;++ const editorRef = useRef(null);+ const [showAddImport, setShowAddImport] = useState(false);+ const [importType, setImportType] = useState<"direct" | "fromModule">(+ "direct"+ );+ const [directImport, setDirectImport] = useState("");+ const [moduleImport, setModuleImport] = useState<ImportState>({+ module: "",+ imports: "",+ });++ const handleComponentUpdate = useCallback(+ (updates: Partial<Component<ComponentConfig>>) => {+ onChange({+ ...component,+ ...updates,+ config: {+ ...component.config,+ ...(updates.config || {}),+ },+ });+ },+ [component, onChange]+ );++ const formatImport = (imp: Import): string => {+ if (!imp) return "";+ if (typeof imp === "string") {+ return imp;+ }+ return `from ${imp.module} import ${imp.imports.join(", ")}`;+ };++ const handleAddImport = () => {+ const currentImports = [...(component.config.global_imports || [])];++ if (importType === "direct" && directImport) {+ currentImports.push(directImport);+ setDirectImport("");+ } else if (+ importType === "fromModule" &&+ moduleImport.module &&+ moduleImport.imports+ ) {+ currentImports.push({+ module: moduleImport.module,+ imports: moduleImport.imports+ .split(",")+ .map((i) => i.trim())+ .filter((i) => i),+ });+ setModuleImport({ module: "", imports: "" });+ }++ handleComponentUpdate({+ config: {+ ...component.config,+ global_imports: currentImports,+ },+ });+ setShowAddImport(false);+ };++ const handleRemoveImport = (index: number) => {+ const newImports = [...(component.config.global_imports || [])];+ newImports.splice(index, 1);+ handleComponentUpdate({+ config: {+ ...component.config,+ global_imports: newImports,+ },+ });+ };++ return (+ <div className="space-y-6">+ <DetailGroup title="Component Details">+ <div className="space-y-4">+ <label className="block">+ <span className="text-sm font-medium text-gray-700">Name</span>+ <Input+ value={component.label || ""}+ onChange={(e) => handleComponentUpdate({ label: e.target.value })}+ placeholder="Tool name"+ className="mt-1"+ />+ </label>++ <label className="block">+ <span className="text-sm font-medium text-gray-700">+ Description+ </span>+ <TextArea+ value={component.description || ""}+ onChange={(e) =>+ handleComponentUpdate({ description: e.target.value })+ }+ placeholder="Tool description"+ rows={4}+ className="mt-1"+ />+ </label>+ </div>+ </DetailGroup>++ <DetailGroup title="Configuration">+ <div className="space-y-4">+ <label className="block">+ <span className="text-sm font-medium text-gray-700">+ Function Name+ </span>+ <Input+ value={component.config.name || ""}+ onChange={(e) =>+ handleComponentUpdate({+ config: { ...component.config, name: e.target.value },+ })+ }+ placeholder="Function name"+ className="mt-1"+ />+ </label>++ <div className="space-y-2">+ <span className="text-sm font-medium text-gray-700">+ Global Imports+ </span>+ <div className="flex flex-wrap gap-2 mt-2">+ {(component.config.global_imports || []).map((imp, index) => (+ <div+ key={index}+ className="flex items-center gap-2 bg-tertiary rounded px-2 py-1"+ >+ <span className="text-sm">{formatImport(imp)}</span>+ <Button+ type="text"+ size="small"+ className="flex items-center justify-center h-6 w-6 p-0"+ onClick={() => handleRemoveImport(index)}+ icon={<MinusCircle className="h-4 w-4" />}+ />+ </div>+ ))}+ </div>++ {showAddImport ? (+ <div className="border rounded p-3 space-y-3">+ <Select+ value={importType}+ onChange={setImportType}+ style={{ width: 200 }}+ >+ <Option value="direct">Direct Import</Option>+ <Option value="fromModule">From Module Import</Option>+ </Select>++ {importType === "direct" ? (+ <Space>+ <Input+ placeholder="Package name (e.g., os)"+ className="w-64"+ value={directImport}+ onChange={(e) => setDirectImport(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && directImport) {+ handleAddImport();+ }+ }}+ />+ <Button onClick={handleAddImport} disabled={!directImport}>+ Add+ </Button>+ </Space>+ ) : (+ <Space direction="vertical" className="w-full">+ <Input+ placeholder="Module name (e.g., typing)"+ className="w-64"+ value={moduleImport.module}+ onChange={(e) =>+ setModuleImport((prev) => ({+ ...prev,+ module: e.target.value,+ }))+ }+ />+ <Space className="w-full">+ <Input+ placeholder="Import names (comma-separated)"+ className="w-64"+ value={moduleImport.imports}+ onChange={(e) =>+ setModuleImport((prev) => ({+ ...prev,+ imports: e.target.value,+ }))+ }+ />+ <Button+ onClick={handleAddImport}+ disabled={!moduleImport.module || !moduleImport.imports}+ >+ Add+ </Button>+ </Space>+ </Space>+ )}+ </div>+ ) : (+ <Button+ type="dashed"+ onClick={() => setShowAddImport(true)}+ className="w-full"+ >+ <PlusCircle className="h-4 w-4 mr-2" />+ Add Import+ </Button>+ )}+ </div>++ <label className="block">+ <span className="text-sm font-medium text-gray-700">+ Source Code+ </span>+ <div className="mt-1 h-96">+ <MonacoEditor+ value={component.config.source_code || ""}+ editorRef={editorRef}+ language="python"+ onChange={(value) =>+ handleComponentUpdate({+ config: { ...component.config, source_code: value },+ })+ }+ />+ </div>+ </label>++ <div className="flex items-center gap-2">+ <span className="text-sm font-medium text-gray-700">+ Has Cancellation Support+ </span>+ <Switch+ checked={component.config.has_cancellation_support || false}+ onChange={(checked) =>+ handleComponentUpdate({+ config: {+ ...component.config,+ has_cancellation_support: checked,+ },+ })+ }+ />+ </div>+ </div>+ </DetailGroup>+ </div>+ );+};++export default React.memo(ToolFields);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 40b419b05..46e5f12c4 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@@ -85,7 +85,7 @@ export const ComponentLibrary: React.FC<LibraryProps> = () => {{title: "Agents",type: "agent" as ComponentTypes,- items: defaultGallery.items.components.agents.map((agent) => ({+ items: defaultGallery.components.agents.map((agent) => ({label: agent.label,config: agent,})),@@ -94,7 +94,7 @@ export const ComponentLibrary: React.FC<LibraryProps> = () => {{title: "Models",type: "model" as ComponentTypes,- items: defaultGallery.items.components.models.map((model) => ({+ items: defaultGallery.components.models.map((model) => ({label: `${model.label || model.config.model}`,config: model,})),@@ -103,7 +103,7 @@ export const ComponentLibrary: React.FC<LibraryProps> = () => {{title: "Tools",type: "tool" as ComponentTypes,- items: defaultGallery.items.components.tools.map((tool) => ({+ items: defaultGallery.components.tools.map((tool) => ({label: tool.config.name,config: tool,})),@@ -112,12 +112,10 @@ export const ComponentLibrary: React.FC<LibraryProps> = () => {{title: "Terminations",type: "termination" as ComponentTypes,- items: defaultGallery.items.components.terminations.map(- (termination) => ({- label: `${termination.label}`,- config: termination,- })- ),+ items: defaultGallery.components.terminations.map((termination) => ({+ label: `${termination.label}`,+ config: termination,+ })),icon: <Timer className="w-4 h-4" />,},],@@ -205,6 +203,7 @@ export const ComponentLibrary: React.FC<LibraryProps> = () => {</div><Collapse+ accordionitems={items}defaultActiveKey={["Agents"]}bordered={false}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.tsxdeleted file mode 100644index e68cc1ffc..000000000--- a/python/packages/autogen-studio/frontend/src/components/views/team/builder/node-editor/node-editor.tsx+++ /dev/null@@ -1,298 +0,0 @@-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 { isComponent } from "../../../../types/guards";-import NodeEditorFields from "./fields/fields";--export 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 (- key !== "global_imports" &&- 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"- size="large"- 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}- editPath={editPath}- workingCopy={workingCopy}- setWorkingCopy={setWorkingCopy}- updateComponentAtPath={updateComponentAtPath}- getCurrentComponent={getCurrentComponent}- />- )}- <div className="flex justify-end gap-2 mt-4 absolute bottom-0 right-0 left-0 p-4 bg-primary 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 a069e6fd9..a75d427c3 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@@ -45,7 +45,7 @@ import {} from "../../../types/guards";// Icon mapping for different node types-const iconMap: Record<+export const iconMap: Record<Component<ComponentConfig>["component_type"],LucideIcon> = {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 952621012..ea73f687b 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,7 +42,7 @@ export const TeamSidebar: React.FC<TeamSidebarProps> = ({const createTeam = () => {const newTeam = Object.assign({},- { component: defaultGallery?.items.teams[0] }+ { component: defaultGallery?.components.teams[0] });newTeam.component.label ="default_team" + new Date().getTime().toString().slice(0, 2);@@ -231,7 +231,7 @@ export const TeamSidebar: React.FC<TeamSidebarProps> = ({From Gallery</div><div key={"gallery_content"} className="scroll overflow-y-auto">- {defaultGallery?.items.teams.map((galleryTeam) => (+ {defaultGallery?.components.teams.map((galleryTeam) => (<divkey={galleryTeam.label + galleryTeam.component_type}className="relative border-secondary"