Skip to content

A programming framework for agentic AI

Add Token Streaming in AGS , Support Env variables (#5659)

Victor Dibiafbe94dd7ed4b
diff --git a/python/packages/autogen-core/docs/src/user-guide/autogenstudio-user-guide/faq.md b/python/packages/autogen-core/docs/src/user-guide/autogenstudio-user-guide/faq.md
index 66034743a..39d94fd72 100644
--- a/python/packages/autogen-core/docs/src/user-guide/autogenstudio-user-guide/faq.md
+++ b/python/packages/autogen-core/docs/src/user-guide/autogenstudio-user-guide/faq.md
@@ -127,15 +127,16 @@ result_stream = tm.run(task="What is the weather in New York?", team_config="te
```
-<!-- ## Q: Can I deploy my agent workflows as APIs?
+You can also load the team specification as an AgentChat object using the `load_component` method.
-Yes. You can launch the workflow as an API endpoint from the command line using the `autogenstudio` commandline tool. For example:
+```python
-```bash
-autogenstudio serve --workflow=workflow.json --port=5000
-```
+import json
+from autogen_agentchat.teams import BaseGroupChat
+team_config = json.load(open("team.json"))
+team = BaseGroupChat.load_component(team_config)
-Similarly, the workflow launch command above can be wrapped into a Dockerfile that can be deployed on cloud services like Azure Container Apps or Azure Web Apps. -->
+```
## Q: Can I run AutoGen Studio in a Docker container?
diff --git a/python/packages/autogen-core/docs/src/user-guide/autogenstudio-user-guide/usage.md b/python/packages/autogen-core/docs/src/user-guide/autogenstudio-user-guide/usage.md
index 9e19f8049..4d1d49363 100644
--- a/python/packages/autogen-core/docs/src/user-guide/autogenstudio-user-guide/usage.md
+++ b/python/packages/autogen-core/docs/src/user-guide/autogenstudio-user-guide/usage.md
@@ -140,6 +140,17 @@ To understand the full configuration of an model clients, you can refer to the [
Note that you can similarly define your model client in Python and call `dump_component()` on it to get the JSON configuration and use it to update the model client section of your team or agent configuration.
+Finally, you can use the `load_component()` method to load a team configuration from a JSON file:
+
+```python
+
+import json
+from autogen_agentchat.teams import BaseGroupChat
+team_config = json.load(open("team.json"))
+team = BaseGroupChat.load_component(team_config)
+
+```
+
## Gallery - Sharing and Reusing Components
AGS provides a Gallery view, where a gallery is a collection of components - teams, agents, models, tools, and terminations - that can be shared and reused across projects.
diff --git a/python/packages/autogen-studio/autogenstudio/database/db_manager.py b/python/packages/autogen-studio/autogenstudio/database/db_manager.py
index 1df428016..dbc58b4d2 100644
--- a/python/packages/autogen-studio/autogenstudio/database/db_manager.py
+++ b/python/packages/autogen-studio/autogenstudio/database/db_manager.py
@@ -32,6 +32,13 @@ class DatabaseManager:
base_dir=base_dir,
)
+ def _should_auto_upgrade(self) -> bool:
+ """
+ Check if auto upgrade should run based on schema differences
+ """
+ needs_upgrade, _ = self.schema_manager.check_schema_status()
+ return needs_upgrade
+
def initialize_database(self, auto_upgrade: bool = False, force_init_alembic: bool = True) -> Response:
"""
Initialize database and migrations in the correct order.
@@ -46,9 +53,7 @@ class DatabaseManager:
try:
inspector = inspect(self.engine)
tables_exist = inspector.get_table_names()
-
if not tables_exist:
- # Fresh install - create tables and initialize migrations
logger.info("Creating database tables...")
SQLModel.metadata.create_all(self.engine)
@@ -57,9 +62,9 @@ class DatabaseManager:
return Response(message="Failed to initialize migrations", status=False)
# Handle existing database
- if auto_upgrade:
+ if auto_upgrade or self._should_auto_upgrade():
logger.info("Checking database schema...")
- if self.schema_manager.ensure_schema_up_to_date(): # <-- Use this instead
+ if self.schema_manager.ensure_schema_up_to_date():
return Response(message="Database schema is up to date", status=True)
return Response(message="Database upgrade failed", status=False)
@@ -129,7 +134,7 @@ class DatabaseManager:
self._init_lock.release()
logger.info("Database reset lock released")
- def upsert(self, model: SQLModel, return_json: bool = True):
+ def upsert(self, model: SQLModel, return_json: bool = True) -> Response:
"""Create or update an entity
Args:
@@ -209,7 +214,7 @@ class DatabaseManager:
return Response(message=status_message, status=status, data=result)
- def delete(self, model_class: SQLModel, filters: dict = None):
+ def delete(self, model_class: SQLModel, filters: dict = None) -> Response:
"""Delete an entity"""
status_message = ""
status = True
diff --git a/python/packages/autogen-studio/autogenstudio/datamodel/__init__.py b/python/packages/autogen-studio/autogenstudio/datamodel/__init__.py
index 435031aab..594982515 100644
--- a/python/packages/autogen-studio/autogenstudio/datamodel/__init__.py
+++ b/python/packages/autogen-studio/autogenstudio/datamodel/__init__.py
@@ -1,12 +1,14 @@
-from .db import Message, Run, RunStatus, Session, Team
+from .db import Gallery, Message, Run, RunStatus, Session, Settings, Team
from .types import (
- Gallery,
+ EnvironmentVariable,
GalleryComponents,
+ GalleryConfig,
GalleryMetadata,
LLMCallEventMessage,
MessageConfig,
MessageMeta,
Response,
+ SettingsConfig,
SocketMessage,
TeamResult,
)
@@ -17,13 +19,18 @@ __all__ = [
"RunStatus",
"Session",
"Team",
+ "Message",
"MessageConfig",
"MessageMeta",
"TeamResult",
"Response",
"SocketMessage",
"LLMCallEventMessage",
- "Gallery",
+ "GalleryConfig",
"GalleryComponents",
"GalleryMetadata",
+ "SettingsConfig",
+ "Settings",
+ "EnvironmentVariable",
+ "Gallery",
]
diff --git a/python/packages/autogen-studio/autogenstudio/datamodel/db.py b/python/packages/autogen-studio/autogenstudio/datamodel/db.py
index 34fed8f04..9aa2cc876 100644
--- a/python/packages/autogen-studio/autogenstudio/datamodel/db.py
+++ b/python/packages/autogen-studio/autogenstudio/datamodel/db.py
@@ -10,7 +10,7 @@ from pydantic import ConfigDict
from sqlalchemy import ForeignKey, Integer
from sqlmodel import JSON, Column, DateTime, Field, SQLModel, func
-from .types import MessageConfig, MessageMeta, TeamResult
+from .types import GalleryConfig, MessageConfig, MessageMeta, SettingsConfig, TeamResult
class Team(SQLModel, table=True):
@@ -47,6 +47,7 @@ class Message(SQLModel, table=True):
default=None, sa_column=Column(Integer, ForeignKey("session.id", ondelete="CASCADE"))
)
run_id: Optional[UUID] = Field(default=None, foreign_key="run.id")
+
message_meta: Optional[Union[MessageMeta, dict]] = Field(default={}, sa_column=Column(JSON))
@@ -103,3 +104,38 @@ class Run(SQLModel, table=True):
messages: Union[List[Message], List[dict]] = Field(default_factory=list, sa_column=Column(JSON))
model_config = ConfigDict(json_encoders={UUID: str, datetime: lambda v: v.isoformat()})
+ user_id: Optional[str] = None
+
+
+class Gallery(SQLModel, table=True):
+ __table_args__ = {"sqlite_autoincrement": True}
+ id: Optional[int] = Field(default=None, primary_key=True)
+ created_at: datetime = Field(
+ default_factory=datetime.now,
+ sa_column=Column(DateTime(timezone=True), server_default=func.now()),
+ ) # pylint: disable=not-callable
+ updated_at: datetime = Field(
+ default_factory=datetime.now,
+ sa_column=Column(DateTime(timezone=True), onupdate=func.now()),
+ ) # pylint: disable=not-callable
+ user_id: Optional[str] = None
+ version: Optional[str] = "0.0.1"
+ config: Union[GalleryConfig, dict] = Field(default_factory=GalleryConfig, sa_column=Column(JSON))
+
+ model_config = ConfigDict(json_encoders={datetime: lambda v: v.isoformat(), UUID: str})
+
+
+class Settings(SQLModel, table=True):
+ __table_args__ = {"sqlite_autoincrement": True}
+ id: Optional[int] = Field(default=None, primary_key=True)
+ created_at: datetime = Field(
+ default_factory=datetime.now,
+ sa_column=Column(DateTime(timezone=True), server_default=func.now()),
+ ) # pylint: disable=not-callable
+ updated_at: datetime = Field(
+ default_factory=datetime.now,
+ sa_column=Column(DateTime(timezone=True), onupdate=func.now()),
+ ) # pylint: disable=not-callable
+ user_id: Optional[str] = None
+ version: Optional[str] = "0.0.1"
+ config: Union[SettingsConfig, dict] = Field(default_factory=SettingsConfig, sa_column=Column(JSON))
diff --git a/python/packages/autogen-studio/autogenstudio/datamodel/types.py b/python/packages/autogen-studio/autogenstudio/datamodel/types.py
index 8475a891e..31767606a 100644
--- a/python/packages/autogen-studio/autogenstudio/datamodel/types.py
+++ b/python/packages/autogen-studio/autogenstudio/datamodel/types.py
@@ -1,10 +1,11 @@
+# from dataclasses import Field
from datetime import datetime
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List, Literal, Optional
from autogen_agentchat.base import TaskResult
from autogen_agentchat.messages import BaseChatMessage
from autogen_core import ComponentModel
-from pydantic import BaseModel
+from pydantic import BaseModel, ConfigDict, Field
class MessageConfig(BaseModel):
@@ -36,8 +37,8 @@ class MessageMeta(BaseModel):
class GalleryMetadata(BaseModel):
author: str
- created_at: datetime
- updated_at: datetime
+ # created_at: datetime = Field(default_factory=datetime.now)
+ # updated_at: datetime = Field(default_factory=datetime.now)
version: str
description: Optional[str] = None
tags: Optional[List[str]] = None
@@ -46,6 +47,12 @@ class GalleryMetadata(BaseModel):
category: Optional[str] = None
last_synced: Optional[datetime] = None
+ model_config = ConfigDict(
+ json_encoders={
+ datetime: lambda v: v.isoformat(),
+ }
+ )
+
class GalleryComponents(BaseModel):
agents: List[ComponentModel]
@@ -55,13 +62,31 @@ class GalleryComponents(BaseModel):
teams: List[ComponentModel]
-class Gallery(BaseModel):
+class GalleryConfig(BaseModel):
id: str
name: str
url: Optional[str] = None
metadata: GalleryMetadata
components: GalleryComponents
+ model_config = ConfigDict(
+ json_encoders={
+ datetime: lambda v: v.isoformat(),
+ }
+ )
+
+
+class EnvironmentVariable(BaseModel):
+ name: str
+ value: str
+ type: Literal["string", "number", "boolean", "secret"] = "string"
+ description: Optional[str] = None
+ required: bool = False
+
+
+class SettingsConfig(BaseModel):
+ environment: List[EnvironmentVariable] = []
+
# web request/response data models
diff --git a/python/packages/autogen-studio/autogenstudio/gallery/builder.py b/python/packages/autogen-studio/autogenstudio/gallery/builder.py
index 78ba42ca3..fb3bc3f05 100644
--- a/python/packages/autogen-studio/autogenstudio/gallery/builder.py
+++ b/python/packages/autogen-studio/autogenstudio/gallery/builder.py
@@ -7,10 +7,12 @@ from autogen_agentchat.teams import RoundRobinGroupChat, SelectorGroupChat
from autogen_core import ComponentModel
from autogen_core.models import ModelInfo
from autogen_ext.agents.web_surfer import MultimodalWebSurfer
+from autogen_ext.code_executors.local import LocalCommandLineCodeExecutor
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_ext.models.openai._openai_client import AzureOpenAIChatCompletionClient
+from autogen_ext.tools.code_execution import PythonCodeExecutionTool
-from autogenstudio.datamodel import Gallery, GalleryComponents, GalleryMetadata
+from autogenstudio.datamodel import GalleryComponents, GalleryConfig, GalleryMetadata
from . import tools as tools
@@ -31,8 +33,6 @@ class GalleryBuilder:
# Default metadata
self.metadata = GalleryMetadata(
author="AutoGen Team",
- created_at=datetime.now(),
- updated_at=datetime.now(),
version="1.0.0",
description="",
tags=[],
@@ -109,12 +109,12 @@ class GalleryBuilder:
self.terminations.append(self._update_component_metadata(termination, label, description))
return self
- def build(self) -> Gallery:
+ def build(self) -> GalleryConfig:
"""Build and return the complete gallery."""
# Update timestamps
- self.metadata.updated_at = datetime.now()
+ # self.metadata.updated_at = datetime.now()
- return Gallery(
+ return GalleryConfig(
id=self.id,
name=self.name,
url=self.url,
@@ -129,7 +129,7 @@ class GalleryBuilder:
)
-def create_default_gallery() -> Gallery:
+def create_default_gallery() -> GalleryConfig:
"""Create a default gallery with all components including calculator and web surfer teams."""
# url = "https://raw.githubusercontent.com/microsoft/autogen/refs/heads/main/python/packages/autogen-studio/autogenstudio/gallery/default.json"
@@ -292,12 +292,6 @@ Read the above conversation. Then select the next role from {participants} to pl
description="A tool that generates images based on a text description using OpenAI's DALL-E model. Note: Requires OpenAI API key to function.",
)
- builder.add_tool(
- tools.generate_pdf_tool.dump_component(),
- label="PDF Generation Tool",
- description="A tool that generates a PDF file from a list of images.Requires the PyFPDF and pillow library to function.",
- )
-
builder.add_tool(
tools.fetch_webpage_tool.dump_component(),
label="Fetch Webpage Tool",
@@ -316,6 +310,14 @@ Read the above conversation. Then select the next role from {participants} to pl
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.",
)
+ code_executor = LocalCommandLineCodeExecutor(work_dir=".coding", timeout=360)
+ code_execution_tool = PythonCodeExecutionTool(code_executor)
+ builder.add_tool(
+ code_execution_tool.dump_component(),
+ label="Python Code Execution Tool",
+ description="A tool that executes Python code in a local environment.",
+ )
+
# Create deep research agent
model_client = OpenAIChatCompletionClient(model="gpt-4o", temperature=0.7)
@@ -353,7 +355,7 @@ Read the above conversation. Then select the next role from {participants} to pl
name="summary_agent",
description="A summary agent that provides a detailed markdown summary of the research as a report to the user.",
model_client=model_client,
- system_message="""You are a summary agent. Your role is to provide a detailed markdown summary of the research as a report to the user. Your report should have a reasonable title that matches the research question and should summarize the key details in the results found in natural an actionable manner. The main results/answer should be in the first paragraph.
+ system_message="""You are a summary agent. Your role is to provide a detailed markdown summary of the research as a report to the user. Your report should have a reasonable title that matches the research question and should summarize the key details in the results found in natural an actionable manner. The main results/answer should be in the first paragraph. Where reasonable, your report should have clear comparison tables that drive critical insights. Most importantly, you should have a reference section and cite the key sources (where available) for facts obtained INSIDE THE MAIN REPORT. Also, where appropriate, you may add images if available that illustrate concepts needed for the summary.
Your report should end with the word "TERMINATE" to signal the end of the conversation.""",
)
diff --git a/python/packages/autogen-studio/autogenstudio/gallery/tools/__init__.py b/python/packages/autogen-studio/autogenstudio/gallery/tools/__init__.py
index 35a0799f7..3d596a15e 100644
--- a/python/packages/autogen-studio/autogenstudio/gallery/tools/__init__.py
+++ b/python/packages/autogen-studio/autogenstudio/gallery/tools/__init__.py
@@ -2,7 +2,6 @@ from .bing_search import bing_search_tool
from .calculator import calculator_tool
from .fetch_webpage import fetch_webpage_tool
from .generate_image import generate_image_tool
-from .generate_pdf import generate_pdf_tool
from .google_search import google_search_tool
__all__ = [
@@ -10,6 +9,5 @@ __all__ = [
"calculator_tool",
"google_search_tool",
"generate_image_tool",
- "generate_pdf_tool",
"fetch_webpage_tool",
]
diff --git a/python/packages/autogen-studio/autogenstudio/gallery/tools/generate_pdf.py b/python/packages/autogen-studio/autogenstudio/gallery/tools/generate_pdf.py
deleted file mode 100644
index caa67ac50..000000000
--- a/python/packages/autogen-studio/autogenstudio/gallery/tools/generate_pdf.py
+++ /dev/null
@@ -1,128 +0,0 @@
-import unicodedata
-import uuid
-from io import BytesIO
-from pathlib import Path
-from typing import Dict, List, Optional
-
-import requests
-from autogen_core.code_executor import ImportFromModule
-from autogen_core.tools import FunctionTool
-from fpdf import FPDF
-from PIL import Image, ImageDraw, ImageOps
-
-
-async def generate_pdf(
- sections: List[Dict[str, Optional[str]]], output_file: str = "report.pdf", report_title: str = "PDF Report"
-) -> str:
- """
- Generate a PDF report with formatted sections including text and images.
-
- Args:
- sections: List of dictionaries containing section details with keys:
- - title: Section title
- - level: Heading level (title, h1, h2)
- - content: Section text content
- - image: Optional image URL or file path
- output_file: Name of output PDF file
- report_title: Title shown at top of report
-
- Returns:
- str: Path to the generated PDF file
- """
-
- def normalize_text(text: str) -> str:
- """Normalize Unicode text to ASCII."""
- return unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode("ascii")
-
- def get_image(image_url_or_path):
- """Fetch image from URL or local path."""
- if image_url_or_path.startswith(("http://", "https://")):
- response = requests.get(image_url_or_path)
- if response.status_code == 200:
- return BytesIO(response.content)
- elif Path(image_url_or_path).is_file():
- return open(image_url_or_path, "rb")
- return None
-
- def add_rounded_corners(img, radius=6):
- """Add rounded corners to an image."""
- mask = Image.new("L", img.size, 0)
- draw = ImageDraw.Draw(mask)
- draw.rounded_rectangle([(0, 0), img.size], radius, fill=255)
- img = ImageOps.fit(img, mask.size, centering=(0.5, 0.5))
- img.putalpha(mask)
- return img
-
- class PDF(FPDF):
- """Custom PDF class with header and content formatting."""
-
- def header(self):
- self.set_font("Arial", "B", 12)
- normalized_title = normalize_text(report_title)
- self.cell(0, 10, normalized_title, 0, 1, "C")
-
- def chapter_title(self, txt):
- self.set_font("Arial", "B", 12)
- normalized_txt = normalize_text(txt)
- self.cell(0, 10, normalized_txt, 0, 1, "L")
- self.ln(2)
-
- def chapter_body(self, body):
- self.set_font("Arial", "", 12)
- normalized_body = normalize_text(body)
- self.multi_cell(0, 10, normalized_body)
- self.ln()
-
- def add_image(self, img_data):
- img = Image.open(img_data)
- img = add_rounded_corners(img)
- img_path = Path(f"temp_{uuid.uuid4().hex}.png")
- img.save(img_path, format="PNG")
- self.image(str(img_path), x=None, y=None, w=190 if img.width > 190 else img.width)
- self.ln(10)
- img_path.unlink()
-
- # Initialize PDF
- pdf = PDF()
- pdf.add_page()
- font_size = {"title": 16, "h1": 14, "h2": 12, "body": 12}
-
- # Add sections
- for section in sections:
- title = section.get("title", "")
- level = section.get("level", "h1")
- content = section.get("content", "")
- image = section.get("image")
-
- pdf.set_font("Arial", "B" if level in font_size else "", font_size.get(level, font_size["body"]))
- pdf.chapter_title(title)
-
- if content:
- pdf.chapter_body(content)
-
- if image:
- img_data = get_image(image)
- if img_data:
- pdf.add_image(img_data)
- if isinstance(img_data, BytesIO):
- img_data.close()
-
- pdf.output(output_file)
- return output_file
-
-
-# Create the PDF generation tool
-generate_pdf_tool = FunctionTool(
- func=generate_pdf,
- description="Generate PDF reports with formatted sections containing text and images",
- global_imports=[
- "uuid",
- "requests",
- "unicodedata",
- ImportFromModule("typing", ("List", "Dict", "Optional")),
- ImportFromModule("pathlib", ("Path",)),
- ImportFromModule("fpdf", ("FPDF",)),
- ImportFromModule("PIL", ("Image", "ImageDraw", "ImageOps")),
- ImportFromModule("io", ("BytesIO",)),
- ],
-)
diff --git a/python/packages/autogen-studio/autogenstudio/teammanager/teammanager.py b/python/packages/autogen-studio/autogenstudio/teammanager/teammanager.py
index d194e351a..c8b4f481b 100644
--- a/python/packages/autogen-studio/autogenstudio/teammanager/teammanager.py
+++ b/python/packages/autogen-studio/autogenstudio/teammanager/teammanager.py
@@ -1,6 +1,7 @@
import asyncio
import json
import logging
+import os
import time
from pathlib import Path
from typing import AsyncGenerator, Callable, List, Optional, Union
@@ -12,7 +13,7 @@ from autogen_agentchat.messages import AgentEvent, ChatMessage
from autogen_core import EVENT_LOGGER_NAME, CancellationToken, Component, ComponentModel
from autogen_core.logging import LLMCallEvent
-from ..datamodel.types import LLMCallEventMessage, TeamResult
+from ..datamodel.types import EnvironmentVariable, LLMCallEventMessage, TeamResult
logger = logging.getLogger(__name__)
@@ -65,7 +66,10 @@ class TeamManager:
return configs
async def _create_team(
- self, team_config: Union[str, Path, dict, ComponentModel], input_func: Optional[Callable] = None
+ self,
+ team_config: Union[str, Path, dict, ComponentModel],
+ input_func: Optional[Callable] = None,
+ env_vars: Optional[List[EnvironmentVariable]] = None,
) -> Component:
"""Create team instance from config"""
if isinstance(team_config, (str, Path)):
@@ -75,6 +79,12 @@ class TeamManager:
else:
config = team_config.model_dump()
+ # Load env vars into environment if provided
+ if env_vars:
+ logger.info("Loading environment variables")
+ for var in env_vars:
+ os.environ[var.name] = var.value
+
team = Team.load_component(config)
for agent in team._participants:
@@ -89,6 +99,7 @@ class TeamManager:
team_config: Union[str, Path, dict, ComponentModel],
input_func: Optional[Callable] = None,
cancellation_token: Optional[CancellationToken] = None,
+ env_vars: Optional[List[EnvironmentVariable]] = None,
) -> AsyncGenerator[Union[AgentEvent | ChatMessage | LLMCallEvent, ChatMessage, TeamResult], None]:
"""Stream team execution results"""
start_time = time.time()
@@ -101,7 +112,7 @@ class TeamManager:
logger.handlers = [llm_event_logger] # Replace all handlers
try:
- team = await self._create_team(team_config, input_func)
+ team = await self._create_team(team_config, input_func, env_vars)
async for message in team.run_stream(task=task, cancellation_token=cancellation_token):
if cancellation_token and cancellation_token.is_cancelled():
@@ -133,13 +144,14 @@ class TeamManager:
team_config: Union[str, Path, dict, ComponentModel],
input_func: Optional[Callable] = None,
cancellation_token: Optional[CancellationToken] = None,
+ env_vars: Optional[List[EnvironmentVariable]] = None,
) -> TeamResult:
"""Run team synchronously"""
start_time = time.time()
team = None
try:
- team = await self._create_team(team_config, input_func)
+ team = await self._create_team(team_config, input_func, env_vars)
result = await team.run(task=task, cancellation_token=cancellation_token)
return TeamResult(task_result=result, usage="", duration=time.time() - start_time)
diff --git a/python/packages/autogen-studio/autogenstudio/web/app.py b/python/packages/autogen-studio/autogenstudio/web/app.py
index 4deccdd90..8fb892e04 100644
--- a/python/packages/autogen-studio/autogenstudio/web/app.py
+++ b/python/packages/autogen-studio/autogenstudio/web/app.py
@@ -13,7 +13,7 @@ from ..version import VERSION
from .config import settings
from .deps import cleanup_managers, init_managers
from .initialization import AppInitializer
-from .routes import runs, sessions, teams, validation, ws
+from .routes import gallery, runs, sessions, settingsroute, teams, validation, ws
# Initialize application
app_file_path = os.path.dirname(os.path.abspath(__file__))
@@ -114,6 +114,20 @@ api.include_router(
responses={404: {"description": "Not found"}},
)
+api.include_router(
+ settingsroute.router,
+ prefix="/settings",
+ tags=["settings"],
+ responses={404: {"description": "Not found"}},
+)
+
+api.include_router(
+ gallery.router,
+ prefix="/gallery",
+ tags=["gallery"],
+ responses={404: {"description": "Not found"}},
+)
+
# Version endpoint
diff --git a/python/packages/autogen-studio/autogenstudio/web/initialization.py b/python/packages/autogen-studio/autogenstudio/web/initialization.py
index 1870506cc..e7830f761 100644
--- a/python/packages/autogen-studio/autogenstudio/web/initialization.py
+++ b/python/packages/autogen-studio/autogenstudio/web/initialization.py
@@ -74,7 +74,7 @@ class AppInitializer:
"""Load environment variables from .env file if it exists"""
env_file = self.app_root / ".env"
if env_file.exists():
- logger.info(f"Loading environment variables from {env_file}")
+ # logger.info(f"Loading environment variables from {env_file}")
load_dotenv(str(env_file))
# Properties for accessing paths
diff --git a/python/packages/autogen-studio/autogenstudio/web/managers/connection.py b/python/packages/autogen-studio/autogenstudio/web/managers/connection.py
index 8ea851918..20ece618d 100644
--- a/python/packages/autogen-studio/autogenstudio/web/managers/connection.py
+++ b/python/packages/autogen-studio/autogenstudio/web/managers/connection.py
@@ -10,6 +10,7 @@ from autogen_agentchat.messages import (
AgentEvent,
ChatMessage,
HandoffMessage,
+ ModelClientStreamingChunkEvent,
MultiModalMessage,
StopMessage,
TextMessage,
@@ -21,7 +22,16 @@ from autogen_core import Image as AGImage
from fastapi import WebSocket, WebSocketDisconnect
from ...database import DatabaseManager
-from ...datamodel import LLMCallEventMessage, Message, MessageConfig, Run, RunStatus, TeamResult
+from ...datamodel import (
+ LLMCallEventMessage,
+ Message,
+ MessageConfig,
+ Run,
+ RunStatus,
+ Settings,
+ SettingsConfig,
+ TeamResult,
+)
from ...teammanager import TeamManager
logger = logging.getLogger(__name__)
@@ -83,6 +93,9 @@ class WebSocketManager:
try:
# Update run with task and status
run = await self._get_run(run_id)
+ # get user Settings
+ user_settings = await self._get_settings(run.user_id)
+ env_vars = SettingsConfig(**user_settings.config).environment if user_settings else None
if run:
run.task = MessageConfig(content=task, source="user").model_dump()
run.status = RunStatus.ACTIVE
@@ -91,7 +104,11 @@ class WebSocketManager:
input_func = self.create_input_func(run_id)
async for message in team_manager.run_stream(
- task=task, team_config=team_config, input_func=input_func, cancellation_token=cancellation_token
+ task=task,
+ team_config=team_config,
+ input_func=input_func,
+ cancellation_token=cancellation_token,
+ env_vars=env_vars,
):
if cancellation_token.is_cancelled() or run_id in self._closed_connections:
logger.info(f"Stream cancelled or connection closed for run {run_id}")
@@ -327,6 +344,8 @@ class WebSocketManager:
"data": message.model_dump(),
"status": "complete",
}
+ elif isinstance(message, ModelClientStreamingChunkEvent):
+ return {"type": "message_chunk", "data": message.model_dump()}
elif isinstance(
message,
@@ -359,6 +378,16 @@ class WebSocketManager:
response = self.db_manager.get(Run, filters={"id": run_id}, return_json=False)
return response.data[0] if response.status and response.data else None
+ async def _get_settings(self, user_id: str) -> Optional[Settings]:
+ """Get user settings from database
+ Args:
+ user_id: User ID to retrieve settings for
+ Returns:
+ Optional[dict]: User settings if found, None otherwise
+ """
+ response = self.db_manager.get(filters={"user_id": user_id}, model_class=Settings, return_json=False)
+ return response.data[0] if response.status and response.data else None
+
async def _update_run_status(self, run_id: UUID, status: RunStatus, error: Optional[str] = None) -> None:
"""Update run status in database
diff --git a/python/packages/autogen-studio/autogenstudio/web/routes/gallery.py b/python/packages/autogen-studio/autogenstudio/web/routes/gallery.py
index 0b0451e53..0aac9703f 100644
--- a/python/packages/autogen-studio/autogenstudio/web/routes/gallery.py
+++ b/python/packages/autogen-studio/autogenstudio/web/routes/gallery.py
@@ -2,61 +2,68 @@
from fastapi import APIRouter, Depends, HTTPException
from ...database import DatabaseManager
-from ...datamodel import Gallery, GalleryConfig, Response, Run, Session
+from ...datamodel import Gallery, Response
+from ...gallery.builder import create_default_gallery
from ..deps import get_db
router = APIRouter()
-async def create_gallery_entry(
- gallery_data: GalleryConfig, user_id: str, db: DatabaseManager = Depends(get_db)
[email protected]("/{gallery_id}")
+async def update_gallery_entry(
+ gallery_id: int, gallery_data: Gallery, user_id: str, db: DatabaseManager = Depends(get_db)
) -> Response:
- # First validate that user owns all runs
- for run in gallery_data.runs:
- run_result = db.get(Run, filters={"id": run.id})
- if not run_result.status or not run_result.data:
- raise HTTPException(status_code=404, detail=f"Run {run.id} not found")
-
- # Get associated session to check ownership
- session_result = db.get(Session, filters={"id": run_result.data[0].session_id})
- if not session_result.status or not session_result.data or session_result.data[0].user_id != user_id:
- raise HTTPException(status_code=403, detail=f"Not authorized to add run {run.id} to gallery")
-
- # Create gallery entry
- gallery = Gallery(user_id=user_id, config=gallery_data)
- result = db.upsert(gallery)
- return result
-
-
[email protected]("/{gallery_id}")
-async def get_gallery_entry(gallery_id: int, user_id: str, db: DatabaseManager = Depends(get_db)) -> Response:
+ # Check ownership first
result = db.get(Gallery, filters={"id": gallery_id})
if not result.status or not result.data:
raise HTTPException(status_code=404, detail="Gallery entry not found")
- gallery = result.data[0]
- if gallery.config["visibility"] != "public" and gallery.user_id != user_id:
- raise HTTPException(status_code=403, detail="Not authorized to view this gallery entry")
+ if result.data[0].user_id != user_id:
+ raise HTTPException(status_code=403, detail="Not authorized to update this gallery entry")
+
+ # Update if authorized
+ gallery_data.id = gallery_id # Ensure ID matches
+ gallery_data.user_id = user_id # Ensure user_id matches
+ return db.upsert(gallery_data)
- return result
+
+async def create_gallery_entry(gallery_data: Gallery, db: DatabaseManager = Depends(get_db)) -> Response:
+ response = db.upsert(gallery_data)
+ if not response.status:
+ raise HTTPException(status_code=400, detail=response.message)
+ return response
@router.get("/")
async def list_gallery_entries(user_id: str, db: DatabaseManager = Depends(get_db)) -> Response:
result = db.get(Gallery, filters={"user_id": user_id})
+ if not result.data or len(result.data) == 0:
+ # create a default gallery entry
+ gallery_config = create_default_gallery()
+ default_gallery = Gallery(user_id=user_id, config=gallery_config.model_dump())
+ db.upsert(default_gallery)
+ result = db.get(Gallery, filters={"user_id": user_id})
+
return result
[email protected]("/{gallery_id}")
+async def get_gallery_entry(gallery_id: int, user_id: str, db: DatabaseManager = Depends(get_db)) -> Response:
+ result = db.get(Gallery, filters={"id": gallery_id, "user_id": user_id})
+ if not result.status or not result.data:
+ raise HTTPException(status_code=404, detail="Gallery entry not found")
+
+ return Response(status=result.status, data=result.data[0], message=result.message)
+
+
@router.delete("/{gallery_id}")
async def delete_gallery_entry(gallery_id: int, user_id: str, db: DatabaseManager = Depends(get_db)) -> Response:
# Check ownership first
- result = db.get(Gallery, filters={"id": gallery_id})
+ result = db.get(Gallery, filters={"id": gallery_id, "user_id": user_id})
+
if not result.status or not result.data:
raise HTTPException(status_code=404, detail="Gallery entry not found")
-
- if result.data[0].user_id != user_id:
- raise HTTPException(status_code=403, detail="Not authorized to delete this gallery entry")
-
+ response = db.delete(Gallery, filters={"id": gallery_id})
# Delete if authorized
- return db.delete(Gallery, filters={"id": gallery_id})
+ return response
diff --git a/python/packages/autogen-studio/autogenstudio/web/routes/runs.py b/python/packages/autogen-studio/autogenstudio/web/routes/runs.py
index 9644099de..d1445b5e1 100644
--- a/python/packages/autogen-studio/autogenstudio/web/routes/runs.py
+++ b/python/packages/autogen-studio/autogenstudio/web/routes/runs.py
@@ -34,6 +34,7 @@ async def create_run(
Run(
session_id=request.session_id,
status=RunStatus.CREATED,
+ user_id=request.user_id,
task=None, # Will be set when run starts
team_result=None,
),
diff --git a/python/packages/autogen-studio/autogenstudio/web/routes/settingsroute.py b/python/packages/autogen-studio/autogenstudio/web/routes/settingsroute.py
new file mode 100644
index 000000000..e4468c957
--- /dev/null
+++ b/python/packages/autogen-studio/autogenstudio/web/routes/settingsroute.py
@@ -0,0 +1,32 @@
+# api/routes/settings.py
+from typing import Dict
+
+from fastapi import APIRouter, Depends, HTTPException
+
+from ...datamodel import Settings, SettingsConfig
+from ..deps import get_db
+
+router = APIRouter()
+
+
+async def get_settings(user_id: str, db=Depends(get_db)) -> Dict:
+ try:
+ response = db.get(Settings, filters={"user_id": user_id})
+ if not response.status or not response.data:
+ # create a default settings
+ config = SettingsConfig(environment=[])
+ default_settings = Settings(user_id=user_id, config=config.model_dump())
+ db.upsert(default_settings)
+ response = db.get(Settings, filters={"user_id": user_id})
+ return {"status": True, "data": response.data[0]}
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e)) from e
+
+
+async def update_settings(settings: Settings, db=Depends(get_db)) -> Dict:
+ response = db.upsert(settings)
+ if not response.status:
+ raise HTTPException(status_code=400, detail=response.message)
+ return {"status": True, "data": response.data}
diff --git a/python/packages/autogen-studio/frontend/package.json b/python/packages/autogen-studio/frontend/package.json
index f711788c1..598577a40 100644
--- a/python/packages/autogen-studio/frontend/package.json
+++ b/python/packages/autogen-studio/frontend/package.json
@@ -47,6 +47,7 @@
"react-dom": "^18.2.0",
"react-markdown": "^9.0.1",
"react-syntax-highlighter": "^15.6.1",
+ "remark-gfm": "^4.0.1",
"tailwindcss": "^3.4.14",
"yarn": "^1.22.22",
"zustand": "^5.0.1"
diff --git a/python/packages/autogen-studio/frontend/src/components/types/datamodel.ts b/python/packages/autogen-studio/frontend/src/components/types/datamodel.ts
index 3e3ad8813..19925902a 100644
--- a/python/packages/autogen-studio/frontend/src/components/types/datamodel.ts
+++ b/python/packages/autogen-studio/frontend/src/components/types/datamodel.ts
@@ -48,6 +48,13 @@ export interface TextMessageConfig extends BaseMessageConfig {
content: string;
}
+export interface BaseAgentEvent extends BaseMessageConfig {}
+
+export interface ModelClientStreamingChunkEvent extends BaseAgentEvent {
+ content: string;
+ type: "ModelClientStreamingChunkEvent";
+}
+
export interface MultiModalMessageConfig extends BaseMessageConfig {
content: (string | ImageContent)[];
}
@@ -75,7 +82,8 @@ export type AgentMessageConfig =
| StopMessageConfig
| HandoffMessageConfig
| ToolCallMessageConfig
- | ToolCallResultMessageConfig;
+ | ToolCallResultMessageConfig
+ | ModelClientStreamingChunkEvent;
export interface FromModuleImport {
module: string;
@@ -136,6 +144,7 @@ export interface AssistantAgentConfig {
system_message?: string;
reflect_on_tool_use: boolean;
tool_call_summary_format: string;
+ model_client_stream: boolean;
}
export interface UserProxyAgentConfig {
@@ -266,7 +275,8 @@ export interface WebSocketMessage {
| "completion"
| "input_request"
| "error"
- | "llm_call_event";
+ | "llm_call_event"
+ | "message_chunk";
data?: AgentMessageConfig | TaskResult;
status?: RunStatus;
error?: string;
@@ -303,3 +313,58 @@ export type RunStatus =
| "complete"
| "error"
| "stopped";
+
+// Settings
+
+export type EnvironmentVariableType =
+ | "string"
+ | "number"
+ | "boolean"
+ | "secret";
+
+export interface EnvironmentVariable {
+ name: string;
+ value: string;
+ type: EnvironmentVariableType;
+ description?: string;
+ required: boolean;
+}
+
+export interface SettingsConfig {
+ environment: EnvironmentVariable[];
+}
+
+export interface Settings extends DBModel {
+ config: SettingsConfig;
+}
+
+export interface GalleryMetadata {
+ author: string;
+ created_at: string;
+ updated_at: string;
+ version: string;
+ description?: string;
+ tags?: string[];
+ license?: string;
+ homepage?: string;
+ category?: string;
+ lastSynced?: string;
+}
+
+export interface GalleryConfig {
+ id: string;
+ name: string;
+ url?: string;
+ metadata: GalleryMetadata;
+ components: {
+ teams: Component<TeamConfig>[];
+ agents: Component<AgentConfig>[];
+ models: Component<ModelConfig>[];
+ tools: Component<ToolConfig>[];
+ terminations: Component<TerminationConfig>[];
+ };
+}
+
+export interface Gallery extends DBModel {
+ config: GalleryConfig;
+}
diff --git a/python/packages/autogen-studio/frontend/src/components/views/atoms.tsx b/python/packages/autogen-studio/frontend/src/components/views/atoms.tsx
index eea5d5f23..b483c4642 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/atoms.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/atoms.tsx
@@ -12,6 +12,7 @@ import {
} from "lucide-react";
import ReactMarkdown from "react-markdown";
import { Tooltip } from "antd";
+import remarkGfm from "remark-gfm";
export const LoadingIndicator = ({ size = 16 }: { size: number }) => (
<div className="inline-flex items-center gap-2 text-accent mr-2">
@@ -95,7 +96,8 @@ export const TruncatableText = memo(
shouldTruncate && !isExpanded
? content.slice(0, threshold) + "..."
: content;
-
+ const proseClassName =
+ " dark:prose-invert prose-table:border-hidden prose-td:border-t prose-th:border-b prose-ul:list-disc prose-sm prose-ol:list-decimal ";
return (
<div className="relative">
<div
@@ -109,7 +111,14 @@ export const TruncatableText = memo(
${className}
`}
>
- <ReactMarkdown>{displayContent}</ReactMarkdown>
+ <ReactMarkdown
+ className={
+ isExpanded ? `mt-4 text-sm text-primary ${proseClassName}` : ""
+ }
+ remarkPlugins={[remarkGfm]}
+ >
+ {displayContent}
+ </ReactMarkdown>
{shouldTruncate && !isExpanded && (
<div className="absolute bottom-0 left-0 right-0 h-24 bg-gradient-to-t from-secondary to-transparent opacity-20" />
)}
@@ -153,7 +162,7 @@ export const TruncatableText = memo(
onClick={() => setIsFullscreen(false)}
>
<div
- className="relative bg-secondary w-full h-full md:w-4/5 md:h-4/5 md:rounded-lg p-8 overflow-auto"
+ className="relative bg-secondary scroll w-full h-full md:w-4/5 md:h-4/5 md:rounded-lg p-8 overflow-auto"
style={{ opacity: 0.95 }}
onClick={(e) => e.stopPropagation()}
>
@@ -166,11 +175,16 @@ export const TruncatableText = memo(
<X size={24} />
</button>
</Tooltip>
- <div className="mt-8 text-base text-primary">
+ <div className={`mt-8 text-base text-primary ${proseClassName}`}>
{isJson ? (
<pre className="whitespace-pre-wrap">{content}</pre>
) : (
- <ReactMarkdown>{content}</ReactMarkdown>
+ <ReactMarkdown
+ className="text-primary"
+ remarkPlugins={[remarkGfm]}
+ >
+ {content}
+ </ReactMarkdown>
)}
</div>
</div>
diff --git a/python/packages/autogen-studio/frontend/src/components/views/gallery/api.ts b/python/packages/autogen-studio/frontend/src/components/views/gallery/api.ts
new file mode 100644
index 000000000..60b5fb35e
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/gallery/api.ts
@@ -0,0 +1,109 @@
+import { Gallery } from "../../types/datamodel";
+import { getServerUrl } from "../../utils";
+
+export class GalleryAPI {
+ private getBaseUrl(): string {
+ return getServerUrl();
+ }
+
+ private getHeaders(): HeadersInit {
+ return {
+ "Content-Type": "application/json",
+ };
+ }
+
+ async listGalleries(userId: string): Promise<Gallery[]> {
+ const response = await fetch(
+ `${this.getBaseUrl()}/gallery/?user_id=${userId}`,
+ {
+ headers: this.getHeaders(),
+ }
+ );
+ const data = await response.json();
+ if (!data.status)
+ throw new Error(data.message || "Failed to fetch galleries");
+ return data.data;
+ }
+
+ async getGallery(galleryId: number, userId: string): Promise<Gallery> {
+ const response = await fetch(
+ `${this.getBaseUrl()}/gallery/${galleryId}?user_id=${userId}`,
+ {
+ headers: this.getHeaders(),
+ }
+ );
+ const data = await response.json();
+ if (!data.status)
+ throw new Error(data.message || "Failed to fetch gallery");
+ return data.data;
+ }
+
+ async createGallery(
+ galleryData: Partial<Gallery>,
+ userId: string
+ ): Promise<Gallery> {
+ const gallery = {
+ ...galleryData,
+ user_id: userId,
+ };
+
+ console.log("Creating gallery with data:", gallery);
+
+ const response = await fetch(`${this.getBaseUrl()}/gallery/`, {
+ method: "POST",
+ headers: this.getHeaders(),
+ body: JSON.stringify(gallery),
+ });
+ const data = await response.json();
+ if (!data.status)
+ throw new Error(data.message || "Failed to create gallery");
+ return data.data;
+ }
+
+ async updateGallery(
+ galleryId: number,
+ galleryData: Partial<Gallery>,
+ userId: string
+ ): Promise<Gallery> {
+ const gallery = {
+ ...galleryData,
+ user_id: userId,
+ };
+
+ const response = await fetch(
+ `${this.getBaseUrl()}/gallery/${galleryId}?user_id=${userId}`,
+ {
+ method: "PUT",
+ headers: this.getHeaders(),
+ body: JSON.stringify(gallery),
+ }
+ );
+ const data = await response.json();
+ if (!data.status)
+ throw new Error(data.message || "Failed to update gallery");
+ return data.data;
+ }
+
+ async deleteGallery(galleryId: number, userId: string): Promise<void> {
+ const response = await fetch(
+ `${this.getBaseUrl()}/gallery/${galleryId}?user_id=${userId}`,
+ {
+ method: "DELETE",
+ headers: this.getHeaders(),
+ }
+ );
+ const data = await response.json();
+ if (!data.status)
+ throw new Error(data.message || "Failed to delete gallery");
+ }
+
+ async syncGallery(url: string): Promise<Gallery> {
+ const response = await fetch(url);
+ if (!response.ok) {
+ throw new Error(`Failed to sync gallery from ${url}`);
+ }
+ return await response.json();
+ }
+}
+
+export const galleryAPI = new GalleryAPI();
diff --git a/python/packages/autogen-studio/frontend/src/components/views/gallery/create-modal.tsx b/python/packages/autogen-studio/frontend/src/components/views/gallery/create-modal.tsx
index 80ff323ad..a6ce5fdd9 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/gallery/create-modal.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/gallery/create-modal.tsx
@@ -3,8 +3,8 @@ import { Modal, Tabs, Input, Button, Alert, Upload } from "antd";
import { Globe, Upload as UploadIcon, Code } from "lucide-react";
import { MonacoEditor } from "../monaco";
import type { InputRef, UploadFile, UploadProps } from "antd";
-import { Gallery } from "./types";
import { defaultGallery } from "./utils";
+import { Gallery, GalleryConfig } from "../../types/datamodel";
interface GalleryCreateModalProps {
open: boolean;
@@ -31,9 +31,11 @@ export const GalleryCreateModal: React.FC<GalleryCreateModalProps> = ({
setError("");
try {
const response = await fetch(url);
- const data = await response.json();
+ const data = (await response.json()) as GalleryConfig;
// TODO: Validate against Gallery schema
- onCreateGallery(data);
+ onCreateGallery({
+ config: data,
+ });
onCancel();
} catch (err) {
setError("Failed to fetch or parse gallery from URL");
@@ -48,9 +50,14 @@ export const GalleryCreateModal: React.FC<GalleryCreateModalProps> = ({
const reader = new FileReader();
reader.onload = (e: ProgressEvent<FileReader>) => {
try {
- const content = JSON.parse(e.target?.result as string);
+ const content = JSON.parse(
+ e.target?.result as string
+ ) as GalleryConfig;
+
// TODO: Validate against Gallery schema
- onCreateGallery(content);
+ onCreateGallery({
+ config: content,
+ });
onCancel();
} catch (err) {
setError("Invalid JSON file");
@@ -64,9 +71,11 @@ export const GalleryCreateModal: React.FC<GalleryCreateModalProps> = ({
const handlePasteImport = () => {
try {
- const content = JSON.parse(jsonContent);
+ const content = JSON.parse(jsonContent) as GalleryConfig;
// TODO: Validate against Gallery schema
- onCreateGallery(content);
+ onCreateGallery({
+ config: content,
+ });
onCancel();
} catch (err) {
setError("Invalid JSON format");
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.json
index 8494cc0a9..08fc16f8f 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-18T16:52:37.999327",
- "updated_at": "2025-02-18T16:52:38.055078",
+ "created_at": "2025-02-21T20:43:06.400850",
+ "updated_at": "2025-02-21T20:43:07.501068",
"version": "1.0.0",
"description": "A default gallery containing basic components for human-in-loop conversations",
"tags": ["human-in-loop", "assistant", "web agents"],
@@ -75,8 +75,8 @@
"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",
+ "description": "An agent that solves tasks by browsing the web using a headless browser.",
+ "label": "Web Surfer Agent",
"config": {
"name": "websurfer_agent",
"model_client": {
@@ -104,8 +104,8 @@
"component_type": "agent",
"version": 1,
"component_version": 1,
- "description": "An agent that provides assistance with tool use.",
- "label": "AssistantAgent",
+ "description": "an agent that verifies and summarizes information",
+ "label": "Verification Assistant",
"config": {
"name": "assistant_agent",
"model_client": {
@@ -414,8 +414,8 @@
"component_type": "termination",
"version": 1,
"component_version": 1,
- "description": null,
- "label": "OrTerminationCondition",
+ "description": "Termination condition that ends the conversation when either a message contains 'TERMINATE' or the maximum number of messages is reached.",
+ "label": "OR Termination",
"config": {
"conditions": [
{
@@ -1024,7 +1024,7 @@
"config": {}
},
"description": "A summary agent that provides a detailed markdown summary of the research as a report to the user.",
- "system_message": "You are a summary agent. Your role is to provide a detailed markdown summary of the research as a report to the user. Your report should have a reasonable title that matches the research question and should summarize the key details in the results found in natural an actionable manner. The main results/answer should be in the first paragraph.\n Your report should end with the word \"TERMINATE\" to signal the end of the conversation.",
+ "system_message": "You are a summary agent. Your role is to provide a detailed markdown summary of the research as a report to the user. Your report should have a reasonable title that matches the research question and should summarize the key details in the results found in natural an actionable manner. The main results/answer should be in the first paragraph. Where reasonable, your report should have clear comparison tables that drive critical insights. Most importantly, you should have a reference section and cite the key sources (where available) for facts obtained INSIDE THE MAIN REPORT. Also, where appropriate, you may add images if available that illustrate concepts needed for the summary.\n Your report should end with the word \"TERMINATE\" to signal the end of the conversation.",
"model_client_stream": false,
"reflect_on_tool_use": false,
"tool_call_summary_format": "{result}"
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.tsx
index 88942fd44..b37232131 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
@@ -11,14 +11,15 @@ import {
Edit,
Copy,
Trash,
+ Plus,
} from "lucide-react";
import { ComponentEditor } from "../team/builder/component-editor/component-editor";
import { TruncatableText } from "../atoms";
-import type { Gallery } from "./types";
import {
Component,
ComponentConfig,
ComponentTypes,
+ Gallery,
} from "../../types/datamodel";
type CategoryKey = `${ComponentTypes}s`;
@@ -34,8 +35,9 @@ const ComponentCard: React.FC<
CardActions & {
item: Component<ComponentConfig>;
index: number;
+ allowDelete: boolean;
}
-> = ({ item, onEdit, onDuplicate, onDelete, index }) => (
+> = ({ item, onEdit, onDuplicate, onDelete, index, allowDelete }) => (
<div
className="bg-secondary rounded overflow-hidden group h-full cursor-pointer"
onClick={() => onEdit(item, index)}
@@ -45,16 +47,18 @@ const ComponentCard: React.FC<
{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);
- }}
- />
+ {allowDelete && (
+ <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"
@@ -98,12 +102,15 @@ const ComponentGrid: React.FC<
} & 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} />
+ <ComponentCard
+ key={idx}
+ item={item}
+ index={idx}
+ allowDelete={items.length > 1}
+ {...actions}
+ />
))}
</div>
</div>
@@ -117,11 +124,29 @@ const iconMap = {
termination: Timer,
} as const;
+// Add default configurations for each component type
+const defaultConfigs: Record<ComponentTypes, ComponentConfig> = {
+ team: { selector_prompt: "Default selector prompt", participants: [] } as any,
+ agent: { name: "New Agent", description: "" } as any,
+ model: { model: "gpt-3.5", api_key: "" } as any,
+ tool: {
+ source_code: "",
+ name: "New Tool",
+ description: "A new tool",
+ global_imports: [],
+ has_cancellation_support: false,
+ },
+ termination: { max_messages: 1 },
+};
+
export const GalleryDetail: React.FC<{
gallery: Gallery;
onSave: (updates: Partial<Gallery>) => void;
onDirtyStateChange: (isDirty: boolean) => void;
}> = ({ gallery, onSave, onDirtyStateChange }) => {
+ if (!gallery.config.components) {
+ return <div className="text-secondary">No components found</div>;
+ }
const [editingComponent, setEditingComponent] = useState<{
component: Component<ComponentConfig>;
category: CategoryKey;
@@ -137,9 +162,12 @@ export const GalleryDetail: React.FC<{
) => {
const updatedGallery = {
...gallery,
- components: {
- ...gallery.components,
- [category]: updater(gallery.components[category]),
+ config: {
+ ...gallery.config,
+ components: {
+ ...gallery.config.components,
+ [category]: updater(gallery.config.components[category]),
+ },
},
};
onSave(updatedGallery);
@@ -158,7 +186,7 @@ export const GalleryDetail: React.FC<{
onDuplicate: (component: Component<ComponentConfig>, index: number) => {
const category = `${activeTab}s` as CategoryKey;
const baseLabel = component.label?.replace(/_\d+$/, "");
- const components = gallery.components[category];
+ const components = gallery.config.components[category];
const nextNumber =
Math.max(
@@ -187,6 +215,41 @@ export const GalleryDetail: React.FC<{
},
};
+ const handleAdd = () => {
+ const category = `${activeTab}s` as CategoryKey;
+ const components = gallery.config.components[category];
+ let newComponent: Component<ComponentConfig>;
+ const newLabel = `New ${
+ activeTab.charAt(0).toUpperCase() + activeTab.slice(1)
+ }`;
+
+ if (components.length > 0) {
+ // Clone the entire component and just modify the label
+ newComponent = {
+ ...components[0], // This preserves all fields (provider, version, description, etc.)
+ label: newLabel,
+ };
+ } else {
+ // Only for empty categories, use default config
+ newComponent = {
+ provider: "new",
+ component_type: activeTab,
+ config: defaultConfigs[activeTab],
+ label: newLabel,
+ };
+ }
+
+ updateGallery(category, (components) => {
+ const newComponents = [...components, newComponent];
+ setEditingComponent({
+ component: newComponent,
+ category,
+ index: newComponents.length - 1,
+ });
+ return newComponents;
+ });
+ };
+
const handleComponentUpdate = (
updatedComponent: Component<ComponentConfig>
) => {
@@ -207,16 +270,36 @@ export const GalleryDetail: React.FC<{
<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})
+ ({gallery.config.components[`${key}s` as CategoryKey].length})
</span>
</span>
),
children: (
- <ComponentGrid
- items={gallery.components[`${key}s` as CategoryKey]}
- title={key}
- {...handlers}
- />
+ <div>
+ <div className="flex justify-between items-center mb-4">
+ <h3 className="text-base font-medium">
+ {gallery.config.components[`${key}s` as CategoryKey].length}{" "}
+ {gallery.config.components[`${key}s` as CategoryKey].length === 1
+ ? key.charAt(0).toUpperCase() + key.slice(1)
+ : key.charAt(0).toUpperCase() + key.slice(1) + "s"}
+ </h3>
+ <Button
+ type="primary"
+ icon={<Plus className="w-4 h-4" />}
+ onClick={() => {
+ setActiveTab(key as ComponentTypes);
+ handleAdd();
+ }}
+ >
+ {`Add ${key.charAt(0).toUpperCase() + key.slice(1)}`}
+ </Button>
+ </div>
+ <ComponentGrid
+ items={gallery.config.components[`${key}s` as CategoryKey]}
+ title={key}
+ {...handlers}
+ />
+ </div>
),
}));
@@ -232,23 +315,23 @@ export const GalleryDetail: React.FC<{
<div>
<div className="flex items-center gap-2">
<h1 className="text-2xl font-medium text-primary">
- {gallery.name}
+ {gallery.config.name}
</h1>
- {gallery.url && (
+ {gallery.config.url && (
<Tooltip title="Remote Gallery">
<Globe className="w-5 h-5 text-secondary" />
</Tooltip>
)}
</div>
<p className="text-secondary w-1/2 mt-2 line-clamp-2">
- {gallery.metadata.description}
+ {gallery.config.metadata.description}
</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.components).reduce(
+ {Object.values(gallery.config.components).reduce(
(sum, arr) => sum + arr.length,
0
)}{" "}
@@ -256,7 +339,7 @@ export const GalleryDetail: React.FC<{
</span>
</div>
<div className="bg-tertiary backdrop-blur rounded p-2 text-sm">
- v{gallery.metadata.version}
+ v{gallery.config.metadata.version}
</div>
</div>
</div>
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.tsx
index dbbc40a14..06bf075b0 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
@@ -1,16 +1,19 @@
-import React, { useEffect, useState } from "react";
+import React, { useCallback, useEffect, useState, useContext } from "react";
import { message, Modal } from "antd";
import { ChevronRight } from "lucide-react";
-import { useGalleryStore } from "./store";
+import { appContext } from "../../../hooks/provider";
+import { galleryAPI } from "./api";
import { GallerySidebar } from "./sidebar";
import { GalleryDetail } from "./detail";
import { GalleryCreateModal } from "./create-modal";
-import type { Gallery } from "./types";
+import type { Gallery } from "../../types/datamodel";
export const GalleryManager: React.FC = () => {
const [isLoading, setIsLoading] = useState(false);
- const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
+ const [galleries, setGalleries] = useState<Gallery[]>([]);
+ const [currentGallery, setCurrentGallery] = useState<Gallery | null>(null);
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
+ const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
const [isSidebarOpen, setIsSidebarOpen] = useState(() => {
if (typeof window !== "undefined") {
const stored = localStorage.getItem("gallerySidebar");
@@ -19,20 +22,8 @@ export const GalleryManager: React.FC = () => {
return true;
});
- const {
- galleries,
- selectedGalleryId,
- selectGallery,
- addGallery,
- updateGallery,
- removeGallery,
- setDefaultGallery,
- getSelectedGallery,
- getDefaultGallery,
- } = useGalleryStore();
-
+ const { user } = useContext(appContext);
const [messageApi, contextHolder] = message.useMessage();
- const currentGallery = getSelectedGallery();
// Persist sidebar state
useEffect(() => {
@@ -41,24 +32,55 @@ export const GalleryManager: React.FC = () => {
}
}, [isSidebarOpen]);
+ const fetchGalleries = useCallback(async () => {
+ if (!user?.email) return;
+
+ try {
+ setIsLoading(true);
+ const data = await galleryAPI.listGalleries(user.email);
+ setGalleries(data);
+ if (!currentGallery && data.length > 0) {
+ setCurrentGallery(data[0]);
+ }
+ } catch (error) {
+ console.error("Error fetching galleries:", error);
+ messageApi.error("Failed to fetch galleries");
+ } finally {
+ setIsLoading(false);
+ }
+ }, [user?.email, currentGallery, messageApi]);
+
+ useEffect(() => {
+ fetchGalleries();
+ }, [fetchGalleries]);
+
// Handle URL params
useEffect(() => {
const params = new URLSearchParams(window.location.search);
const galleryId = params.get("galleryId");
- if (galleryId && !selectedGalleryId) {
- handleSelectGallery(galleryId);
+ if (galleryId && !currentGallery) {
+ const numericId = parseInt(galleryId, 10);
+ if (!isNaN(numericId)) {
+ handleSelectGallery(numericId);
+ }
}
}, []);
// Update URL when gallery changes
useEffect(() => {
- if (selectedGalleryId) {
- window.history.pushState({}, "", `?galleryId=${selectedGalleryId}`);
+ if (currentGallery?.id) {
+ window.history.pushState(
+ {},
+ "",
+ `?galleryId=${currentGallery.id.toString()}`
+ );
}
- }, [selectedGalleryId]);
+ }, [currentGallery?.id]);
+
+ const handleSelectGallery = async (galleryId: number) => {
+ if (!user?.email) return;
- const handleSelectGallery = async (galleryId: string) => {
if (hasUnsavedChanges) {
Modal.confirm({
title: "Unsaved Changes",
@@ -66,71 +88,129 @@ export const GalleryManager: React.FC = () => {
okText: "Discard",
cancelText: "Go Back",
onOk: () => {
- selectGallery(galleryId);
+ switchToGallery(galleryId);
setHasUnsavedChanges(false);
},
});
} else {
- selectGallery(galleryId);
+ await switchToGallery(galleryId);
}
};
- const handleCreateGallery = async (galleryData: Gallery) => {
- const newGallery: Gallery = {
- id: `gallery_${Date.now()}`,
- name: galleryData.name || "New Gallery",
- url: galleryData.url,
- metadata: {
- ...galleryData.metadata,
- created_at: new Date().toISOString(),
- updated_at: new Date().toISOString(),
- },
- components: galleryData.components || {
- teams: [],
- agents: [],
- models: [],
- tools: [],
- terminations: [],
- },
- };
+ const switchToGallery = async (galleryId: number) => {
+ if (!user?.email) return;
+ setIsLoading(true);
try {
- setIsLoading(true);
- await addGallery(newGallery);
- messageApi.success("Gallery created successfully");
- selectGallery(newGallery.id);
+ const data = await galleryAPI.getGallery(galleryId, user.email);
+ setCurrentGallery(data);
} catch (error) {
- messageApi.error("Failed to create gallery");
- console.error(error);
+ console.error("Error loading gallery:", error);
+ messageApi.error("Failed to load gallery");
} finally {
setIsLoading(false);
}
};
- const handleDeleteGallery = async (galleryId: string) => {
+ const handleCreateGallery = async (galleryData: Gallery) => {
+ if (!user?.email) return;
+
+ galleryData.user_id = user.email;
try {
- await removeGallery(galleryId);
- messageApi.success("Gallery deleted successfully");
+ const savedGallery = await galleryAPI.createGallery(
+ galleryData,
+ user.email
+ );
+ setGalleries([savedGallery, ...galleries]);
+ setCurrentGallery(savedGallery);
+ setIsCreateModalOpen(false);
+ messageApi.success("Gallery created successfully");
} catch (error) {
- messageApi.error("Failed to delete gallery");
- console.error(error);
+ console.error("Error creating gallery:", error);
+ messageApi.error("Failed to create gallery");
}
};
- const handleUpdateGallery = async (
- galleryId: string,
- updates: Partial<Gallery>
- ) => {
+ const handleUpdateGallery = async (updates: Partial<Gallery>) => {
+ if (!user?.email || !currentGallery?.id) return;
+
try {
- await updateGallery(galleryId, updates);
+ const sanitizedUpdates = {
+ ...updates,
+ created_at: undefined,
+ updated_at: undefined,
+ };
+ const updatedGallery = await galleryAPI.updateGallery(
+ currentGallery.id,
+ sanitizedUpdates,
+ user.email
+ );
+ setGalleries(
+ galleries.map((g) => (g.id === updatedGallery.id ? updatedGallery : g))
+ );
+ setCurrentGallery(updatedGallery);
setHasUnsavedChanges(false);
messageApi.success("Gallery updated successfully");
} catch (error) {
+ console.error("Error updating gallery:", error);
messageApi.error("Failed to update gallery");
- console.error(error);
}
};
+ const handleDeleteGallery = async (galleryId: number) => {
+ if (!user?.email) return;
+
+ try {
+ await galleryAPI.deleteGallery(galleryId, user.email);
+ setGalleries(galleries.filter((g) => g.id !== galleryId));
+ if (currentGallery?.id === galleryId) {
+ setCurrentGallery(null);
+ }
+ messageApi.success("Gallery deleted successfully");
+ } catch (error) {
+ console.error("Error deleting gallery:", error);
+ messageApi.error("Failed to delete gallery");
+ }
+ };
+
+ const handleSyncGallery = async (galleryId: number) => {
+ if (!user?.email) return;
+
+ try {
+ setIsLoading(true);
+ const gallery = galleries.find((g) => g.id === galleryId);
+ if (!gallery?.config.url) return;
+
+ const remoteGallery = await galleryAPI.syncGallery(gallery.config.url);
+ await handleUpdateGallery({
+ ...remoteGallery,
+ id: galleryId,
+ config: {
+ ...remoteGallery.config,
+ metadata: {
+ ...remoteGallery.config.metadata,
+ lastSynced: new Date().toISOString(),
+ },
+ },
+ });
+
+ messageApi.success("Gallery synced successfully");
+ } catch (error) {
+ console.error("Error syncing gallery:", error);
+ messageApi.error("Failed to sync gallery");
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ if (!user?.email) {
+ return (
+ <div className="flex items-center justify-center h-[calc(100vh-120px)] text-secondary">
+ Please log in to view galleries
+ </div>
+ );
+ }
+
return (
<div className="relative flex h-full w-full">
{contextHolder}
@@ -153,18 +233,17 @@ export const GalleryManager: React.FC = () => {
galleries={galleries}
currentGallery={currentGallery}
onToggle={() => setIsSidebarOpen(!isSidebarOpen)}
- onSelectGallery={(gallery) => handleSelectGallery(gallery.id)}
+ onSelectGallery={(gallery) => handleSelectGallery(gallery.id!)}
onCreateGallery={() => setIsCreateModalOpen(true)}
onDeleteGallery={handleDeleteGallery}
- defaultGalleryId={getDefaultGallery()?.id}
- onSetDefault={setDefaultGallery}
+ onSyncGallery={handleSyncGallery}
isLoading={isLoading}
/>
</div>
{/* Main Content */}
<div
- className={`flex-1 transition-all max-w-5xl -mr-6 duration-200 ${
+ className={`flex-1 transition-all -mr-6 duration-200 ${
isSidebarOpen ? "ml-64" : "ml-12"
}`}
>
@@ -175,18 +254,22 @@ export const GalleryManager: React.FC = () => {
{currentGallery && (
<>
<ChevronRight className="w-4 h-4 text-secondary" />
- <span className="text-secondary">{currentGallery.name}</span>
+ <span className="text-secondary">
+ {currentGallery.config.name}
+ </span>
</>
)}
</div>
{/* Content Area */}
- {currentGallery ? (
+ {isLoading && !currentGallery ? (
+ <div className="flex items-center justify-center h-[calc(100vh-120px)] text-secondary">
+ Loading galleries...
+ </div>
+ ) : currentGallery ? (
<GalleryDetail
gallery={currentGallery}
- onSave={(updates) =>
- handleUpdateGallery(currentGallery.id, updates)
- }
+ onSave={handleUpdateGallery}
onDirtyStateChange={setHasUnsavedChanges}
/>
) : (
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.tsx
index a58908c0a..09fb9dd0c 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
@@ -1,19 +1,17 @@
import React from "react";
-import { Button, Tooltip, Tag } from "antd";
+import { Button, Tooltip } from "antd";
import {
Plus,
Trash2,
PanelLeftClose,
PanelLeftOpen,
- Pin,
Package,
RefreshCw,
Globe,
Info,
} from "lucide-react";
-import type { Gallery } from "./types";
+import type { Gallery } from "../../types/datamodel";
import { getRelativeTimeString } from "../atoms";
-import { useGalleryStore } from "./store";
interface GallerySidebarProps {
isOpen: boolean;
@@ -22,10 +20,9 @@ interface GallerySidebarProps {
onToggle: () => void;
onSelectGallery: (gallery: Gallery) => void;
onCreateGallery: () => void;
- onDeleteGallery: (galleryId: string) => void;
- onSetDefault: (galleryId: string) => void;
+ onDeleteGallery: (galleryId: number) => void;
+ onSyncGallery: (galleryId: number) => void;
isLoading?: boolean;
- defaultGalleryId: string;
}
export const GallerySidebar: React.FC<GallerySidebarProps> = ({
@@ -36,12 +33,9 @@ export const GallerySidebar: React.FC<GallerySidebarProps> = ({
onSelectGallery,
onCreateGallery,
onDeleteGallery,
- onSetDefault,
- defaultGalleryId,
+ onSyncGallery,
isLoading = false,
}) => {
- const { syncGallery, getLastSyncTime } = useGalleryStore();
-
// Render collapsed state
if (!isOpen) {
return (
@@ -109,168 +103,116 @@ export const GallerySidebar: React.FC<GallerySidebarProps> = ({
</div>
{/* Section Label */}
- <div className="py-2 text-sm text-secondary">All Galleries</div>
+ <div className="py-2 flex text-sm text-secondary">
+ <div className="flex">All Galleries</div>
+ {isLoading && <RefreshCw className="w-4 h-4 ml-2 animate-spin" />}
+ </div>
{/* Galleries List */}
- {isLoading ? (
- <div className="p-4 text-center text-secondary text-sm">Loading...</div>
- ) : galleries.length === 0 ? (
- <div className="p-4 text-center text-secondary text-sm">
+ {!isLoading && galleries.length === 0 && (
+ <div className="p-2 mr-2 text-center text-secondary text-sm border border-dashed rounded">
+ <Info className="w-4 h-4 inline-block mr-1.5 -mt-0.5" />
No galleries found
</div>
- ) : (
- <div className="scroll overflow-y-auto h-[calc(100%-170px)]">
- <>
- {galleries.map((gallery) => (
- <div key={gallery.id} className="relative border-secondary">
- <div
- className={`absolute top-1 left-0.5 z-50 h-[calc(100%-8px)] w-1 bg-opacity-80 rounded ${
- currentGallery?.id === gallery.id
- ? "bg-accent"
- : "bg-tertiary"
- }`}
- />
- <div
- className={`group ml-1 flex flex-col p-3 rounded-l cursor-pointer hover:bg-secondary ${
- currentGallery?.id === gallery.id
- ? "border-accent bg-secondary"
- : "border-transparent"
- }`}
- onClick={() => onSelectGallery(gallery)}
- >
- {/* Gallery Name and Actions Row */}
- <div className="flex items-center justify-between min-w-0">
- {" "}
- {/* Added min-w-0 */}
- <div className="flex items-center gap-2 min-w-0 flex-1">
- {" "}
- {/* Added min-w-0 and flex-1 */}
- <div className="truncate flex-1">
- {" "}
- {/* Wrapped name in div with truncate and flex-1 */}
- <span className="font-medium">{gallery.name}</span>
- </div>
- {gallery.url && (
- <Tooltip title="Remote Gallery">
- <Globe className="w-3 h-3 text-secondary flex-shrink-0" />{" "}
- {/* Added flex-shrink-0 */}
- </Tooltip>
- )}
+ )}
+
+ <div className="scroll overflow-y-auto h-[calc(100%-170px)]">
+ {galleries.map((gallery) => (
+ <div key={gallery.id} className="relative border-secondary">
+ <div
+ className={`absolute top-1 left-0.5 z-50 h-[calc(100%-8px)] w-1 bg-opacity-80 rounded ${
+ currentGallery?.id === gallery.id ? "bg-accent" : "bg-tertiary"
+ }`}
+ />
+ {gallery && gallery.config && gallery.config.components && (
+ <div
+ className={`group ml-1 flex flex-col p-3 rounded-l cursor-pointer hover:bg-secondary ${
+ currentGallery?.id === gallery.id
+ ? "border-accent bg-secondary"
+ : "border-transparent"
+ }`}
+ onClick={() => onSelectGallery(gallery)}
+ >
+ {/* Gallery Name and Actions Row */}
+ <div className="flex items-center justify-between min-w-0">
+ <div className="flex items-center gap-2 min-w-0 flex-1">
+ <div className="truncate flex-1">
+ <span className="font-medium">{gallery.config.name}</span>
</div>
- <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity ml-2 flex-shrink-0">
- {gallery.url && (
- <Tooltip
- title={
- getLastSyncTime(gallery.id)
- ? `Last synced: ${getLastSyncTime(gallery.id)}`
- : "Never synced"
- }
- >
- <Button
- type="text"
- size="small"
- className="p-0 min-w-[24px] h-6"
- icon={<RefreshCw className="w-4 h-4" />}
- onClick={(e) => {
- e.stopPropagation();
- syncGallery(gallery.id);
- }}
- />
- </Tooltip>
- )}
- <Tooltip
- title={
- defaultGalleryId === gallery.id
- ? "Default gallery"
- : "Set as default gallery"
- }
- >
- <Button
- type="text"
- size="small"
- className={`p-0 min-w-[24px] h-6 ${
- defaultGalleryId === gallery.id ? "text-accent" : ""
- }`}
- icon={
- <Pin
- className={`w-4 h-4 ${
- defaultGalleryId === gallery.id
- ? "fill-accent"
- : ""
- }`}
- />
- }
- onClick={(e) => {
- e.stopPropagation();
- onSetDefault(gallery.id);
- }}
- />
+ {gallery.config.url && (
+ <Tooltip title="Remote Gallery">
+ <Globe className="w-3 h-3 text-secondary flex-shrink-0" />
</Tooltip>
- <Tooltip
- title={
- galleries.length === 1
- ? "Cannot delete the last gallery"
- : "Delete gallery"
- }
- >
+ )}
+ </div>
+ <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity ml-2 flex-shrink-0">
+ {gallery.config.url && (
+ <Tooltip title="Sync gallery">
<Button
type="text"
size="small"
className="p-0 min-w-[24px] h-6"
- danger
- disabled={galleries.length === 1}
- icon={<Trash2 className="w-4 h-4 text-red-500" />}
+ icon={<RefreshCw className="w-4 h-4" />}
onClick={(e) => {
e.stopPropagation();
- onDeleteGallery(gallery.id);
+ onSyncGallery(gallery.id!);
}}
/>
</Tooltip>
- </div>
+ )}
+ <Tooltip
+ title={
+ galleries.length === 1
+ ? "Cannot delete the last gallery"
+ : "Delete gallery"
+ }
+ >
+ <Button
+ type="text"
+ size="small"
+ className="p-0 min-w-[24px] h-6"
+ danger
+ disabled={galleries.length === 1}
+ icon={<Trash2 className="w-4 h-4 text-red-500" />}
+ onClick={(e) => {
+ e.stopPropagation();
+ onDeleteGallery(gallery.id!);
+ }}
+ />
+ </Tooltip>
</div>
+ </div>
- {/* Rest of the content remains the same */}
- <div className="mt-1 flex items-center gap-2 text-xs text-secondary">
- <span className="bg-secondary/20 truncate rounded px-1">
- v{gallery.metadata.version}
+ {/* Gallery Metadata */}
+ <div className="mt-1 flex items-center gap-2 text-xs text-secondary">
+ <span className="bg-secondary/20 truncate rounded px-1">
+ v{gallery.config.metadata.version}
+ </span>
+ <div className="flex items-center gap-1">
+ <Package className="w-3 h-3" />
+ <span>
+ {Object.values(gallery.config.components).reduce(
+ (sum, arr) => sum + arr.length,
+ 0
+ )}{" "}
+ components
</span>
- <div className="flex items-center gap-1">
- <Package className="w-3 h-3" />
- <span>
- {Object.values(gallery.components).reduce(
- (sum, arr) => sum + arr.length,
- 0
- )}{" "}
- components
- </span>
- </div>
</div>
+ </div>
- {/* Updated Timestamp */}
+ {/* Updated Timestamp */}
+ {gallery.updated_at && (
<div className="mt-1 flex items-center gap-1 text-xs text-secondary">
- <span>
- {getRelativeTimeString(gallery.metadata.updated_at)}
- {defaultGalleryId === gallery.id ? (
- <span className="text-accent border-accent border rounded px-1 ml-1 py-0.5">
- default
- </span>
- ) : (
- ""
- )}
- </span>
+ <span>{getRelativeTimeString(gallery.updated_at)}</span>
</div>
- </div>
+ )}
</div>
- ))}
- </>
-
- <div className="p-2 mt-2 border-dashed border rounded text-xs mr-2">
- Gallery items marked as default (
- <Pin className="w-4 h-4 inline-block -mt-0.5" />) are available in
- the builder by default.
+ )}
</div>
- </div>
- )}
+ ))}
+ </div>
</div>
);
};
+
+export default GallerySidebar;
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.tsx
index 951c5e225..79088545f 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
@@ -1,162 +1,53 @@
import { create } from "zustand";
-import { persist } from "zustand/middleware";
-import { Gallery } from "./types";
-import {
- AgentConfig,
- Component,
- ModelConfig,
- TeamConfig,
- TerminationConfig,
- ToolConfig,
-} from "../../types/datamodel";
-import { defaultGallery } from "./utils";
+import { Gallery } from "../../types/datamodel";
+import { galleryAPI } from "./api";
-interface GalleryStore {
+interface GalleryState {
+ // State
galleries: Gallery[];
- defaultGalleryId: string;
- selectedGalleryId: string | null;
+ selectedGallery: Gallery | null;
+ isLoading: boolean;
+ error: string | null;
- addGallery: (gallery: Gallery) => void;
- updateGallery: (id: string, gallery: Partial<Gallery>) => void;
- removeGallery: (id: string) => void;
- setDefaultGallery: (id: string) => void;
- selectGallery: (id: string) => void;
- getDefaultGallery: () => Gallery;
+ // Actions
+ fetchGalleries: (userId: string) => Promise<void>;
+ selectGallery: (gallery: Gallery) => void;
getSelectedGallery: () => Gallery | null;
- syncGallery: (id: string) => Promise<void>;
- getLastSyncTime: (id: string) => string | null;
- getGalleryComponents: () => {
- teams: Component<TeamConfig>[];
- components: {
- agents: Component<AgentConfig>[];
- models: Component<ModelConfig>[];
- tools: Component<ToolConfig>[];
- terminations: Component<TerminationConfig>[];
- };
- };
}
-export const useGalleryStore = create<GalleryStore>()(
- persist(
- (set, get) => ({
- galleries: [defaultGallery],
- defaultGalleryId: defaultGallery.id,
- selectedGalleryId: defaultGallery.id,
-
- addGallery: (gallery) =>
- set((state) => {
- if (state.galleries.find((g) => g.id === gallery.id)) return state;
- return {
- galleries: [gallery, ...state.galleries],
- defaultGalleryId: state.defaultGalleryId || gallery.id,
- selectedGalleryId: state.selectedGalleryId || gallery.id,
- };
- }),
-
- updateGallery: (id, updates) =>
- set((state) => ({
- galleries: state.galleries.map((gallery) =>
- gallery.id === id
- ? {
- ...gallery,
- ...updates,
- metadata: {
- ...gallery.metadata,
- ...updates.metadata,
- updated_at: new Date().toISOString(),
- },
- }
- : gallery
- ),
- })),
-
- removeGallery: (id) =>
- set((state) => {
- if (state.galleries.length <= 1) return state;
-
- const newGalleries = state.galleries.filter((g) => g.id !== id);
- const updates: Partial<GalleryStore> = {
- galleries: newGalleries,
- };
-
- if (id === state.defaultGalleryId) {
- updates.defaultGalleryId = newGalleries[0].id;
- }
-
- if (id === state.selectedGalleryId) {
- updates.selectedGalleryId = newGalleries[0].id;
- }
-
- return updates;
- }),
-
- setDefaultGallery: (id) =>
- set((state) => {
- const gallery = state.galleries.find((g) => g.id === id);
- if (!gallery) return state;
- return { defaultGalleryId: id };
- }),
-
- selectGallery: (id) =>
- set((state) => {
- const gallery = state.galleries.find((g) => g.id === id);
- if (!gallery) return state;
- return { selectedGalleryId: id };
- }),
-
- getDefaultGallery: () => {
- const { galleries, defaultGalleryId } = get();
- return galleries.find((g) => g.id === defaultGalleryId)!;
- },
-
- getSelectedGallery: () => {
- const { galleries, selectedGalleryId } = get();
- if (!selectedGalleryId) return null;
- return galleries.find((g) => g.id === selectedGalleryId) || null;
- },
-
- syncGallery: async (id) => {
- const gallery = get().galleries.find((g) => g.id === id);
- if (!gallery?.url) return;
-
- try {
- const response = await fetch(gallery.url);
- const remoteGallery = await response.json();
-
- get().updateGallery(id, {
- ...remoteGallery,
- id, // preserve local id
- metadata: {
- ...remoteGallery.metadata,
- lastSynced: new Date().toISOString(),
- },
- });
- } catch (error) {
- console.error("Failed to sync gallery:", error);
- throw error;
- }
- },
+export const useGalleryStore = create<GalleryState>((set, get) => ({
+ // Initial state
+ galleries: [],
+ selectedGallery: null,
+ isLoading: false,
+ error: null,
+
+ // Actions
+ fetchGalleries: async (userId: string) => {
+ try {
+ set({ isLoading: true, error: null });
+ const galleries = await galleryAPI.listGalleries(userId);
+
+ set({
+ galleries,
+ // Automatically select first gallery if none selected
+ selectedGallery: get().selectedGallery || galleries[0] || null,
+ isLoading: false,
+ });
+ } catch (error) {
+ set({
+ error:
+ error instanceof Error ? error.message : "Failed to fetch galleries",
+ isLoading: false,
+ });
+ }
+ },
- getLastSyncTime: (id) => {
- const gallery = get().galleries.find((g) => g.id === id);
- return gallery?.metadata.lastSynced ?? null;
- },
+ selectGallery: (gallery: Gallery) => {
+ set({ selectedGallery: gallery });
+ },
- getGalleryComponents: () => {
- const defaultGallery = get().getDefaultGallery();
- return {
- teams: defaultGallery.components.teams,
- components: {
- agents: defaultGallery.components.agents,
- models: defaultGallery.components.models,
- tools: defaultGallery.components.tools,
- terminations: defaultGallery.components.terminations,
- },
- };
- },
- }),
- {
- name: "gallery-storage-v8",
- }
- )
-);
+ getSelectedGallery: () => {
+ return get().selectedGallery;
+ },
+}));
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.ts
index 479d89af5..47763d07b 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/gallery/types.ts
+++ b/python/packages/autogen-studio/frontend/src/components/views/gallery/types.ts
@@ -1,43 +1,9 @@
-import {
- AgentConfig,
- Component,
- ModelConfig,
- TeamConfig,
- TerminationConfig,
- ToolConfig,
-} from "../../types/datamodel";
+import { Gallery } from "../../types/datamodel";
-export interface GalleryMetadata {
- author: string;
- created_at: string;
- updated_at: string;
- version: string;
- description?: string;
- tags?: string[];
- license?: string;
- homepage?: string;
- category?: string;
- lastSynced?: string;
-}
-
-export interface Gallery {
- id: string;
- name: string;
- url?: string;
- metadata: GalleryMetadata;
- components: {
- teams: Component<TeamConfig>[];
- agents: Component<AgentConfig>[];
- models: Component<ModelConfig>[];
- tools: Component<ToolConfig>[];
- terminations: Component<TerminationConfig>[];
- };
-}
-
-export interface GalleryAPI {
- listGalleries: () => Promise<Gallery[]>;
- getGallery: (id: string) => Promise<Gallery>;
- createGallery: (gallery: Gallery) => Promise<Gallery>;
- updateGallery: (gallery: Gallery) => Promise<Gallery>;
- deleteGallery: (id: string) => Promise<void>;
-}
+// export interface GalleryAPI {
+// listGalleries: () => Promise<Gallery[]>;
+// getGallery: (id: string) => Promise<Gallery>;
+// createGallery: (gallery: Gallery) => Promise<Gallery>;
+// updateGallery: (gallery: Gallery) => Promise<Gallery>;
+// deleteGallery: (id: string) => Promise<void>;
+// }
diff --git a/python/packages/autogen-studio/frontend/src/components/views/gallery/utils.ts b/python/packages/autogen-studio/frontend/src/components/views/gallery/utils.ts
index d8dc75bc1..ceef18fca 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/gallery/utils.ts
+++ b/python/packages/autogen-studio/frontend/src/components/views/gallery/utils.ts
@@ -1,15 +1,15 @@
-import { Gallery } from "./types";
+import { GalleryConfig } from "../../types/datamodel";
// Load and parse the gallery JSON file
-const loadGalleryFromJson = (): Gallery => {
+const loadGalleryFromJson = (): GalleryConfig => {
try {
// You can adjust the path to your JSON file as needed
const galleryJson = require("./default_gallery.json");
- return galleryJson as Gallery;
+ return galleryJson as GalleryConfig;
} catch (error) {
console.error("Error loading gallery JSON:", error);
throw error;
}
};
-export const defaultGallery: Gallery = loadGalleryFromJson();
+export const defaultGallery: GalleryConfig = loadGalleryFromJson();
diff --git a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/chat.tsx b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/chat.tsx
index e5b3bd11d..a9f1583f7 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/chat.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/chat.tsx
@@ -12,6 +12,7 @@ import {
TeamResult,
Session,
Component,
+ ModelClientStreamingChunkEvent,
} from "../../../types/datamodel";
import { appContext } from "../../../../hooks/provider";
import ChatInput from "./chatinput";
@@ -40,6 +41,11 @@ export default function ChatView({ session }: ChatViewProps) {
const [messageApi, contextHolder] = message.useMessage();
const chatContainerRef = React.useRef<HTMLDivElement | null>(null);
+ const [streamingContent, setStreamingContent] = React.useState<{
+ runId: string;
+ content: string;
+ source: string;
+ } | null>(null);
// Context and config
const { user } = React.useContext(appContext);
@@ -161,7 +167,25 @@ export default function ChatView({ session }: ChatViewProps) {
}
console.log("Error: ", message.error);
+ case "message_chunk":
+ if (!message.data) return current;
+
+ // Update streaming content
+ try {
+ const chunk = message.data as ModelClientStreamingChunkEvent;
+ setStreamingContent((prev) => ({
+ runId: current.id,
+ content: (prev?.content || "") + (chunk.content || ""),
+ source: chunk.source || "assistant",
+ }));
+ } catch (error) {
+ console.error("Error parsing message chunk:", error);
+ }
+
+ return current; // Keep current run unchanged
+
case "message":
+ setStreamingContent(null);
if (!message.data) return current;
// Create new Message object from websocket data
@@ -521,6 +545,7 @@ export default function ChatView({ session }: ChatViewProps) {
onInputResponse={handleInputResponse}
onCancel={handleCancel}
isFirstRun={existingRuns.length === 0}
+ streamingContent={streamingContent}
/>
)}
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.tsx
index 35b261448..f4a3a1476 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
@@ -146,7 +146,7 @@ const LLMLogRenderer: React.FC<LLMLogRendererProps> = ({ content }) => {
}
}, [content]);
- console.log(parsedContent);
+ // console.log(parsedContent);
if (!parsedContent) {
return (
diff --git a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/runview.tsx b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/runview.tsx
index 96ffcefeb..99cbc527b 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/runview.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/runview.tsx
@@ -26,8 +26,52 @@ interface RunViewProps {
onInputResponse?: (response: string) => void;
onCancel?: () => void;
isFirstRun?: boolean;
+ streamingContent?: {
+ runId: string;
+ content: string;
+ source: string;
+ } | null;
}
+interface StreamingMessageProps {
+ content: string;
+ source: string;
+}
+
+const StreamingMessage: React.FC<StreamingMessageProps> = ({
+ content,
+ source,
+}) => {
+ const [showCursor, setShowCursor] = useState(true);
+
+ // Blinking cursor effect
+ useEffect(() => {
+ const interval = setInterval(() => {
+ setShowCursor((prev) => !prev);
+ }, 530);
+ return () => clearInterval(interval);
+ }, []);
+
+ return (
+ <div className="flex items-start gap-2 p-2 rounded bg-tertiary border border-secondary transition-all duration-200 mb-6">
+ <div className="p-1.5 rounded bg-light text-primary">
+ <Bot size={14} />
+ </div>
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-semibold text-primary">{source}</span>
+ </div>
+ <div className="text-sm text-secondary break-all">
+ {content}
+ {showCursor && (
+ <span className="inline-block w-2 h-4 ml-1 bg-accent/70 animate-pulse" />
+ )}
+ </div>
+ </div>
+ </div>
+ );
+};
+
export const getAgentMessages = (messages: Message[]): Message[] => {
return messages.filter((msg) => msg.config.source !== "llm_call_event");
};
@@ -51,6 +95,7 @@ const RunView: React.FC<RunViewProps> = ({
onCancel,
teamConfig,
isFirstRun = false,
+ streamingContent,
}) => {
const [isExpanded, setIsExpanded] = useState(true);
const threadContainerRef = useRef<HTMLDivElement | null>(null);
@@ -78,8 +123,7 @@ const RunView: React.FC<RunViewProps> = ({
});
}
}, 450);
- }, [run.messages]); // Only depend on messages changing
- // console.log("run", run);
+ }, [run.messages, streamingContent]);
const calculateThreadTokens = (messages: Message[]) => {
// console.log("messages", messages);
return messages.reduce((total, msg) => {
@@ -312,6 +356,15 @@ const RunView: React.FC<RunViewProps> = ({
/>
</div>
))}
+ {streamingContent &&
+ streamingContent.runId === run.id && (
+ <div className="mr-2 mb-10">
+ <StreamingMessage
+ content={streamingContent.content}
+ source={streamingContent.source}
+ />
+ </div>
+ )}
{/* Input Request UI */}
{run.status === "awaiting_input" && onInputResponse && (
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.tsx
index c0be689ee..907fd4003 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
@@ -27,7 +27,7 @@ export const SessionManager: React.FC = () => {
const { user } = useContext(appContext);
const { session, setSession, sessions, setSessions } = useConfigStore();
- const defaultGallery = useGalleryStore((state) => state.getDefaultGallery());
+ const defaultGallery = useGalleryStore((state) => state.getSelectedGallery());
useEffect(() => {
if (typeof window !== "undefined") {
@@ -196,7 +196,7 @@ export const SessionManager: React.FC = () => {
if (teamsData.length > 0) {
setTeams(teamsData);
} else {
- const sampleTeam = defaultGallery.components.teams[0];
+ const sampleTeam = defaultGallery?.config.components.teams[0];
// If no teams, create a default team
const defaultTeam = await teamAPI.createTeam(
{
diff --git a/python/packages/autogen-studio/frontend/src/components/views/playground/sidebar.tsx b/python/packages/autogen-studio/frontend/src/components/views/playground/sidebar.tsx
index 44530aba1..77e432e4c 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/playground/sidebar.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/playground/sidebar.tsx
@@ -8,6 +8,7 @@ import {
PanelLeftOpen,
InfoIcon,
RefreshCcw,
+ History,
} from "lucide-react";
import type { Session, Team } from "../../types/datamodel";
import { getRelativeTimeString } from "../atoms";
@@ -102,11 +103,15 @@ export const Sidebar: React.FC<SidebarProps> = ({
</div>
<div className="py-2 flex text-sm text-secondary">
- Recents{" "}
- <span className="text-accent text-xs mx-1 mt-0.5">
- {" "}
- ({sessions.length}){" "}
- </span>{" "}
+ <History className="w-4 h-4 inline-block mr-1.5" />
+ <div className="inline-block -mt-0.5">
+ Recents{" "}
+ <span className="text-accent text-xs mx-1 mt-0.5">
+ {" "}
+ ({sessions.length}){" "}
+ </span>{" "}
+ </div>
+
{isLoading && (
<RefreshCcw className="w-4 h-4 inline-block ml-2 animate-spin" />
)}
diff --git a/python/packages/autogen-studio/frontend/src/components/views/settings/api.ts b/python/packages/autogen-studio/frontend/src/components/views/settings/api.ts
new file mode 100644
index 000000000..535c8f404
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/settings/api.ts
@@ -0,0 +1,48 @@
+import { Settings } from "../../types/datamodel";
+import { getServerUrl } from "../../utils";
+
+export class SettingsAPI {
+ private getBaseUrl(): string {
+ return getServerUrl();
+ }
+
+ private getHeaders(): HeadersInit {
+ return {
+ "Content-Type": "application/json",
+ };
+ }
+
+ async getSettings(userId: string): Promise<Settings> {
+ const response = await fetch(
+ `${this.getBaseUrl()}/settings/?user_id=${userId}`,
+ {
+ headers: this.getHeaders(),
+ }
+ );
+ const data = await response.json();
+ if (!data.status)
+ throw new Error(data.message || "Failed to fetch settings");
+ return data.data;
+ }
+
+ async updateSettings(settings: Settings, userId: string): Promise<Settings> {
+ const settingsData = {
+ ...settings,
+ user_id: settings.user_id || userId,
+ };
+
+ console.log("settingsData", settingsData);
+
+ const response = await fetch(`${this.getBaseUrl()}/settings/`, {
+ method: "PUT",
+ headers: this.getHeaders(),
+ body: JSON.stringify(settingsData),
+ });
+ const data = await response.json();
+ if (!data.status)
+ throw new Error(data.message || "Failed to update settings");
+ return data.data;
+ }
+}
+
+export const settingsAPI = new SettingsAPI();
diff --git a/python/packages/autogen-studio/frontend/src/components/views/settings/environment.tsx b/python/packages/autogen-studio/frontend/src/components/views/settings/environment.tsx
new file mode 100644
index 000000000..9d5f27626
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/settings/environment.tsx
@@ -0,0 +1,238 @@
+import React, { useState, useEffect, useContext } from "react";
+import { Button, Input, Select, Table, Switch, message, Tooltip } from "antd";
+import { Plus, Trash2, Save } from "lucide-react";
+import { appContext } from "../../../hooks/provider";
+import { settingsAPI } from "./api";
+import {
+ Settings,
+ EnvironmentVariable,
+ EnvironmentVariableType,
+} from "../../types/datamodel";
+
+const DEFAULT_SETTINGS: Settings = {
+ config: {
+ environment: [],
+ },
+};
+
+export const EnvironmentVariables: React.FC = () => {
+ const [settings, setSettings] = useState<Settings>(DEFAULT_SETTINGS);
+ const [loading, setLoading] = useState(true);
+ const [isDirty, setIsDirty] = useState(false);
+ const [messageApi, contextHolder] = message.useMessage();
+
+ const { user } = useContext(appContext);
+ const userId = user?.email || "";
+
+ useEffect(() => {
+ loadSettings();
+ }, []);
+
+ const loadSettings = async () => {
+ try {
+ setLoading(true);
+ const data = await settingsAPI.getSettings(userId);
+ setSettings(data);
+ setIsDirty(false);
+ } catch (error) {
+ console.error("Failed to load settings:", error);
+ setSettings(DEFAULT_SETTINGS);
+ messageApi.error("Failed to load environment variables");
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const handleAddVariable = () => {
+ const newVar: EnvironmentVariable = {
+ name: "",
+ value: "",
+ type: "string",
+ required: false,
+ };
+
+ const newSettings = {
+ ...settings,
+ config: {
+ ...settings.config,
+ environment: [...settings.config.environment, newVar],
+ },
+ };
+
+ setSettings(newSettings);
+ handleSave(newSettings);
+ };
+
+ const handleSave = async (settingsToSave: Settings) => {
+ try {
+ const sanitizedSettings = {
+ id: settingsToSave.id,
+ config: settingsToSave.config,
+ user_id: userId,
+ };
+ await settingsAPI.updateSettings(sanitizedSettings, userId);
+ setIsDirty(false);
+ messageApi.success("Environment variables saved successfully");
+ } catch (error) {
+ console.error("Failed to save settings:", error);
+ messageApi.error("Failed to save environment variables");
+ }
+ };
+
+ const updateEnvironmentVariable = (
+ index: number,
+ updates: Partial<EnvironmentVariable>
+ ) => {
+ const newEnv = [...settings.config.environment];
+ newEnv[index] = { ...newEnv[index], ...updates };
+ setSettings({
+ ...settings,
+ config: { ...settings.config, environment: newEnv },
+ });
+ setIsDirty(true);
+ };
+
+ const ENVIRONMENT_VARIABLE_TYPES: EnvironmentVariableType[] = [
+ "string",
+ "number",
+ "boolean",
+ "secret",
+ ];
+
+ const columns = [
+ {
+ title: "Name",
+ dataIndex: "name",
+ key: "name",
+ render: (text: string, _: EnvironmentVariable, index: number) => (
+ <Input
+ value={text}
+ placeholder="Variable name"
+ onChange={(e) =>
+ updateEnvironmentVariable(index, { name: e.target.value })
+ }
+ />
+ ),
+ },
+ {
+ title: "Value",
+ dataIndex: "value",
+ key: "value",
+ render: (_: string, record: EnvironmentVariable, index: number) => (
+ <Input.Password
+ value={record.value}
+ placeholder="Variable value"
+ onChange={(e) =>
+ updateEnvironmentVariable(index, { value: e.target.value })
+ }
+ visibilityToggle
+ />
+ ),
+ },
+ {
+ title: "Type",
+ dataIndex: "type",
+ key: "type",
+ render: (text: string, _: EnvironmentVariable, index: number) => (
+ <Select<EnvironmentVariableType>
+ value={text as EnvironmentVariableType}
+ style={{ width: 120 }}
+ onChange={(value) =>
+ updateEnvironmentVariable(index, { type: value })
+ }
+ options={ENVIRONMENT_VARIABLE_TYPES.map((type) => ({
+ value: type,
+ label: type.charAt(0).toUpperCase() + type.slice(1),
+ }))}
+ />
+ ),
+ },
+ {
+ title: "Required",
+ dataIndex: "required",
+ key: "required",
+ render: (value: boolean, _: EnvironmentVariable, index: number) => (
+ <Tooltip title={value ? "Mark as optional" : "Mark as required"}>
+ <Switch
+ checked={value}
+ onChange={(checked) =>
+ updateEnvironmentVariable(index, { required: checked })
+ }
+ />
+ </Tooltip>
+ ),
+ },
+ {
+ title: "Actions",
+ key: "actions",
+ render: (_: any, __: any, index: number) => (
+ <Tooltip title="Delete variable">
+ <Button
+ type="text"
+ danger
+ icon={<Trash2 className="w-4 h-4" />}
+ onClick={() => {
+ const newEnv = [...settings.config.environment];
+ newEnv.splice(index, 1);
+ setSettings({
+ ...settings,
+ config: { ...settings.config, environment: newEnv },
+ });
+ setIsDirty(true);
+ // save
+ handleSave({
+ ...settings,
+ config: { ...settings.config, environment: newEnv },
+ });
+ }}
+ />
+ </Tooltip>
+ ),
+ },
+ ];
+
+ return (
+ <div className="space-y-4">
+ {contextHolder}
+ <div className="flex justify-between items-center">
+ <h3 className="text-lg font-medium"> </h3>
+ <div className="space-x-2 inline-flex">
+ <Tooltip title="Add new variable">
+ <Button
+ type="primary"
+ icon={<Plus className="w-4 h-4" />}
+ onClick={handleAddVariable}
+ >
+ Add
+ </Button>
+ </Tooltip>
+ <Tooltip title={isDirty ? "Save your changes" : "No unsaved changes"}>
+ <Button
+ type="primary"
+ icon={
+ <div className="relative">
+ <Save className="w-4 h-4" />
+ {isDirty && (
+ <div className="absolute -top-1 -right-1 w-2 h-2 bg-red-500 rounded-full" />
+ )}
+ </div>
+ }
+ onClick={() => handleSave(settings)}
+ >
+ Save
+ </Button>
+ </Tooltip>
+ </div>
+ </div>
+ <Table
+ loading={loading}
+ dataSource={settings.config.environment}
+ columns={columns}
+ rowKey={(record) => record.name + record.value}
+ pagination={false}
+ />
+ </div>
+ );
+};
+
+export default EnvironmentVariables;
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.tsx
index 0ab511e79..088981acb 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
@@ -1,11 +1,12 @@
import React, { useState, useEffect } from "react";
-import { ChevronRight, RotateCcw } from "lucide-react";
+import { ChevronRight, RotateCcw, TriangleAlert, Variable } from "lucide-react";
import { Switch, Button, Tooltip } from "antd";
import { MessagesSquare } from "lucide-react";
import { useSettingsStore } from "./store";
import { SettingsSidebar } from "./sidebar";
import { SettingsSection } from "./types";
import { LucideIcon } from "lucide-react";
+import { EnvironmentVariables } from "./environment";
interface SettingToggleProps {
checked: boolean;
@@ -47,13 +48,13 @@ const SectionHeader: React.FC<SectionHeaderProps> = ({
<Icon className="text-accent" size={20} />
<h2 className="text-lg font-semibold">{title}</h2>
</div>
- <Tooltip title="Reset section settings">
+ {/* <Tooltip title="Reset section settings">
<Button
icon={<RotateCcw className="w-4 h-4" />}
onClick={onReset}
type="text"
/>
- </Tooltip>
+ </Tooltip> */}
</div>
);
@@ -85,7 +86,7 @@ export const SettingsManager: React.FC = () => {
icon={MessagesSquare}
onReset={resetPlaygroundSettings}
/>
- <div className="space-y-2 rounded border border-secondary">
+ <div className="space-y-2 rounded border border-secondary">
<SettingToggle
checked={playground.showLLMEvents}
onChange={(checked) =>
@@ -95,6 +96,41 @@ export const SettingsManager: React.FC = () => {
description="Display detailed LLM call logs in the message thread"
/>
</div>
+ <div className="mt-12 pt-6 border-t border-secondary">
+ <p className="text-xs text-secondary">
+ These settings are automatically saved and synced across browser
+ sessions
+ </p>
+ </div>
+ </>
+ ),
+ },
+ {
+ id: "environment",
+ title: "Environment Variables",
+ icon: Variable,
+ content: () => (
+ <>
+ <SectionHeader
+ title="Environment Variables"
+ icon={Variable}
+ onReset={() => {
+ /* Add reset handler */
+ }}
+ />
+ <div>
+ <EnvironmentVariables />
+ <div className="mt-12 pt-6 border-t border-secondary">
+ <p className="text-xs text-secondary">
+ <TriangleAlert
+ strokeWidth={1.5}
+ className="inline-block mr-1 h-4 w-4 "
+ />{" "}
+ Note: Environment variables are currently available to all
+ processes on the server.
+ </p>
+ </div>
+ </div>
</>
),
},
@@ -139,21 +175,6 @@ export const SettingsManager: React.FC = () => {
</div>
<currentSection.content />
-
- <div className="mt-12 pt-6 border-t border-secondary flex justify-between items-center">
- <p className="text-xs text-secondary">
- Settings are automatically saved and synced across browser
- sessions
- </p>
- <Button
- type="text"
- danger
- icon={<RotateCcw className="w-4 h-4 mr-1" />}
- onClick={resetAllSettings}
- >
- Reset All Settings
- </Button>
- </div>
</div>
</div>
</div>
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.tsx
index 5a8159b4c..beede8241 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
@@ -155,7 +155,7 @@ export const TeamBuilder: React.FC<TeamBuilderProps> = ({
handleValidate();
return () => {
- console.log("cleanup component");
+ // console.log("cleanup component");
setValidationResults(null);
};
}, [team, setNodes, setEdges]);
@@ -544,7 +544,7 @@ export const TeamBuilder: React.FC<TeamBuilderProps> = ({
nodes.find((n) => n.id === selectedNodeId)!.data.component
}
onChange={(updatedComponent) => {
- console.log("builder updating component", updatedComponent);
+ // console.log("builder updating component", updatedComponent);
if (selectedNodeId) {
updateNode(selectedNodeId, {
component: updatedComponent,
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.tsx
index 445cc3959..a44fd5453 100644
--- 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.tsx
@@ -147,7 +147,7 @@ export const ComponentEditor: React.FC<ComponentEditorProps> = ({
editPath,
updates
);
- console.log("updatedComponent", updatedComponent);
+
setWorkingCopy(updatedComponent);
// onChange(updatedComponent);
},
diff --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.tsx
index 4034a88ea..8be2942c2 100644
--- 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.tsx
@@ -1,10 +1,11 @@
import React, { useCallback } from "react";
import { Input, Switch, Button, Tooltip } from "antd";
-import { Edit, HelpCircle, Trash2 } from "lucide-react";
+import { Edit, HelpCircle, Trash2, PlusCircle } from "lucide-react";
import {
Component,
ComponentConfig,
AgentConfig,
+ FunctionToolConfig,
} from "../../../../../types/datamodel";
import {
isAssistantAgent,
@@ -19,6 +20,11 @@ interface AgentFieldsProps {
component: Component<AgentConfig>;
onChange: (updates: Partial<Component<ComponentConfig>>) => void;
onNavigate?: (componentType: string, id: string, parentField: string) => void;
+ workingCopy?: Component<ComponentConfig> | null;
+ setWorkingCopy?: (component: Component<ComponentConfig> | null) => void;
+ editPath?: any[];
+ updateComponentAtPath?: any;
+ getCurrentComponent?: any;
}
const InputWithTooltip: React.FC<{
@@ -44,6 +50,11 @@ export const AgentFields: React.FC<AgentFieldsProps> = ({
component,
onChange,
onNavigate,
+ workingCopy,
+ setWorkingCopy,
+ editPath,
+ updateComponentAtPath,
+ getCurrentComponent,
}) => {
if (!component) return null;
@@ -83,116 +94,57 @@ export const AgentFields: React.FC<AgentFieldsProps> = ({
[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>
- )}
+ const handleAddTool = useCallback(() => {
+ if (!isAssistantAgent(component)) return;
- {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>
- );
- }
+ 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 (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>
- );
- }
+ // Update both working copy and actual component state
+ const currentTools = component.config.tools || [];
+ const updatedTools = [...currentTools, blankTool];
+
+ // Update the actual component state
+ handleConfigUpdate("tools", updatedTools);
- return (
- <div className="text-sm text-gray-500 text-center">
- No nested components
- </div>
- );
- };
+ // If working copy functionality is available, update that too
+ if (
+ workingCopy &&
+ setWorkingCopy &&
+ updateComponentAtPath &&
+ getCurrentComponent &&
+ editPath
+ ) {
+ const updatedCopy = updateComponentAtPath(workingCopy, editPath, {
+ config: {
+ ...getCurrentComponent(workingCopy)?.config,
+ tools: updatedTools,
+ },
+ });
+ setWorkingCopy(updatedCopy);
+ }
+ }, [
+ component,
+ handleConfigUpdate,
+ workingCopy,
+ setWorkingCopy,
+ updateComponentAtPath,
+ getCurrentComponent,
+ editPath,
+ ]);
return (
<div className="space-y-6">
@@ -225,10 +177,6 @@ export const AgentFields: React.FC<AgentFieldsProps> = ({
</div>
</DetailGroup>
- <DetailGroup title="Nested Components">
- {renderNestedComponents()}
- </DetailGroup>
-
<DetailGroup title="Configuration">
<div className="space-y-4">
{isAssistantAgent(component) && (
@@ -244,6 +192,45 @@ export const AgentFields: React.FC<AgentFieldsProps> = ({
/>
</InputWithTooltip>
+ {/* Model Client Section */}
+
+ <div className="space-y-2">
+ <span className="text-sm font-medium text-primary">
+ Model Client
+ </span>
+ {component.config.model_client ? (
+ <div className="bg-secondary p-1 px-2 rounded-md">
+ <div className="flex items-center justify-between">
+ {" "}
+ <span className="text-sm">
+ {component.config.model_client.config.model}
+ </span>
+ <div className="flex items-center justify-between">
+ {component.config.model_client && onNavigate && (
+ <Button
+ type="text"
+ icon={<Edit className="w-4 h-4" />}
+ onClick={() =>
+ onNavigate(
+ "model",
+ component.config.model_client?.label || "",
+ "model_client"
+ )
+ }
+ >
+ Configure Model
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+ ) : (
+ <div className="text-sm text-secondary text-center bg-secondary/50 p-4 rounded-md">
+ No model configured
+ </div>
+ )}
+ </div>
+
<InputWithTooltip
label="System Message"
tooltip="System message for the agent"
@@ -257,6 +244,64 @@ export const AgentFields: React.FC<AgentFieldsProps> = ({
/>
</InputWithTooltip>
+ {/* Tools Section */}
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium text-primary">
+ Tools
+ </span>
+ <Button
+ type="dashed"
+ size="small"
+ onClick={handleAddTool}
+ icon={<PlusCircle className="w-4 h-4" />}
+ >
+ Add Tool
+ </Button>
+ </div>
+ <div className="space-y-2">
+ {component.config.tools?.map((tool, index) => (
+ <div
+ key={(tool.label || "") + index}
+ className="bg-secondary p-1 px-2 rounded-md"
+ >
+ <div className="flex items-center justify-between">
+ <span className="text-sm">
+ {tool.config.name || tool.label || ""}
+ </span>
+ <div className="flex items-center gap-2">
+ {onNavigate && (
+ <Button
+ type="text"
+ icon={<Edit className="w-4 h-4" />}
+ onClick={() =>
+ onNavigate(
+ "tool",
+ tool.config.name || tool.label || "",
+ "tools"
+ )
+ }
+ />
+ )}
+ <Button
+ type="text"
+ danger
+ icon={<Trash2 className="w-4 h-4" />}
+ onClick={() => handleRemoveTool(index)}
+ />
+ </div>
+ </div>
+ </div>
+ ))}
+ {(!component.config.tools ||
+ component.config.tools.length === 0) && (
+ <div className="text-sm text-secondary text-center bg-secondary/50 p-4 rounded-md">
+ No tools configured
+ </div>
+ )}
+ </div>
+ </div>
+
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-primary">
Reflect on Tool Use
@@ -269,6 +314,18 @@ export const AgentFields: React.FC<AgentFieldsProps> = ({
/>
</div>
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium text-primary">
+ Stream Model Client
+ </span>
+ <Switch
+ checked={component.config.model_client_stream}
+ onChange={(checked) =>
+ handleConfigUpdate("model_client_stream", checked)
+ }
+ />
+ </div>
+
<InputWithTooltip
label="Tool Call Summary Format"
tooltip="Format for tool call summaries"
@@ -312,7 +369,114 @@ export const AgentFields: React.FC<AgentFieldsProps> = ({
onChange={(e) => handleConfigUpdate("name", e.target.value)}
/>
</InputWithTooltip>
- {/* Add other web surfer fields here */}
+ <InputWithTooltip
+ label="Start Page"
+ tooltip="URL to start browsing from"
+ >
+ <Input
+ value={component.config.start_page || ""}
+ onChange={(e) =>
+ handleConfigUpdate("start_page", e.target.value)
+ }
+ />
+ </InputWithTooltip>
+ <InputWithTooltip
+ label="Downloads Folder"
+ tooltip="Folder path to save downloads"
+ >
+ <Input
+ value={component.config.downloads_folder || ""}
+ onChange={(e) =>
+ handleConfigUpdate("downloads_folder", e.target.value)
+ }
+ />
+ </InputWithTooltip>
+ <InputWithTooltip
+ label="Debug Directory"
+ tooltip="Directory for debugging logs"
+ >
+ <Input
+ value={component.config.debug_dir || ""}
+ onChange={(e) =>
+ handleConfigUpdate("debug_dir", e.target.value)
+ }
+ />
+ </InputWithTooltip>
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium text-primary">
+ Headless
+ </span>
+ <Switch
+ checked={component.config.headless || false}
+ onChange={(checked) =>
+ handleConfigUpdate("headless", checked)
+ }
+ />
+ </div>
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium text-primary">
+ Animate Actions
+ </span>
+ <Switch
+ checked={component.config.animate_actions || false}
+ onChange={(checked) =>
+ handleConfigUpdate("animate_actions", checked)
+ }
+ />
+ </div>
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium text-primary">
+ Save Screenshots
+ </span>
+ <Switch
+ checked={component.config.to_save_screenshots || false}
+ onChange={(checked) =>
+ handleConfigUpdate("to_save_screenshots", checked)
+ }
+ />
+ </div>
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium text-primary">
+ Use OCR
+ </span>
+ <Switch
+ checked={component.config.use_ocr || false}
+ onChange={(checked) => handleConfigUpdate("use_ocr", checked)}
+ />
+ </div>
+ <InputWithTooltip
+ label="Browser Channel"
+ tooltip="Channel for the browser (e.g. beta, stable)"
+ >
+ <Input
+ value={component.config.browser_channel || ""}
+ onChange={(e) =>
+ handleConfigUpdate("browser_channel", e.target.value)
+ }
+ />
+ </InputWithTooltip>
+ <InputWithTooltip
+ label="Browser Data Directory"
+ tooltip="Directory for browser profile data"
+ >
+ <Input
+ value={component.config.browser_data_dir || ""}
+ onChange={(e) =>
+ handleConfigUpdate("browser_data_dir", e.target.value)
+ }
+ />
+ </InputWithTooltip>
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium text-primary">
+ Resize Viewport
+ </span>
+ <Switch
+ checked={component.config.to_resize_viewport || false}
+ onChange={(checked) =>
+ handleConfigUpdate("to_resize_viewport", checked)
+ }
+ />
+ </div>
</>
)}
</div>
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.tsx
index 46e5f12c4..817281de7 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
@@ -74,7 +74,7 @@ const PresetItem: React.FC<PresetItemProps> = ({
export const ComponentLibrary: React.FC<LibraryProps> = () => {
const [searchTerm, setSearchTerm] = React.useState("");
const [isMinimized, setIsMinimized] = React.useState(false);
- const defaultGallery = useGalleryStore((state) => state.getDefaultGallery());
+ const defaultGallery = useGalleryStore((state) => state.getSelectedGallery());
if (!defaultGallery) {
return null;
@@ -85,7 +85,7 @@ export const ComponentLibrary: React.FC<LibraryProps> = () => {
{
title: "Agents",
type: "agent" as ComponentTypes,
- items: defaultGallery.components.agents.map((agent) => ({
+ items: defaultGallery.config.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.components.models.map((model) => ({
+ items: defaultGallery.config.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.components.tools.map((tool) => ({
+ items: defaultGallery.config.components.tools.map((tool) => ({
label: tool.config.name,
config: tool,
})),
@@ -112,10 +112,12 @@ export const ComponentLibrary: React.FC<LibraryProps> = () => {
{
title: "Terminations",
type: "termination" as ComponentTypes,
- items: defaultGallery.components.terminations.map((termination) => ({
- label: `${termination.label}`,
- config: termination,
- })),
+ items: defaultGallery.config.components.terminations.map(
+ (termination) => ({
+ label: `${termination.label}`,
+ config: termination,
+ })
+ ),
icon: <Timer className="w-4 h-4" />,
},
],
diff --git a/python/packages/autogen-studio/frontend/src/components/views/team/manager.tsx b/python/packages/autogen-studio/frontend/src/components/views/team/manager.tsx
index 5cce11ff2..e36c3a425 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/team/manager.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/team/manager.tsx
@@ -3,6 +3,7 @@ import { message, Modal } from "antd";
import { ChevronRight } from "lucide-react";
import { appContext } from "../../../hooks/provider";
import { teamAPI } from "./api";
+import { useGalleryStore } from "../gallery/store";
import { TeamSidebar } from "./sidebar";
import type { Team } from "../../types/datamodel";
import { TeamBuilder } from "./builder/builder";
@@ -22,6 +23,14 @@ export const TeamManager: React.FC = () => {
const [messageApi, contextHolder] = message.useMessage();
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
+ // Initialize galleries
+ const fetchGalleries = useGalleryStore((state) => state.fetchGalleries);
+ useEffect(() => {
+ if (user?.email) {
+ fetchGalleries(user.email);
+ }
+ }, [user?.email, fetchGalleries]);
+
// Persist sidebar state
useEffect(() => {
if (typeof window !== "undefined") {
@@ -36,7 +45,6 @@ export const TeamManager: React.FC = () => {
setIsLoading(true);
const data = await teamAPI.listTeams(user.email);
setTeams(data);
- // console.log("team data", data);
if (!currentTeam && data.length > 0) {
setCurrentTeam(data[0]);
}
@@ -45,7 +53,7 @@ export const TeamManager: React.FC = () => {
} finally {
setIsLoading(false);
}
- }, [user?.email]);
+ }, [user?.email, currentTeam]);
useEffect(() => {
fetchTeams();
@@ -61,20 +69,6 @@ export const TeamManager: React.FC = () => {
}
}, []);
- useEffect(() => {
- const handleLocationChange = () => {
- const params = new URLSearchParams(window.location.search);
- const teamId = params.get("teamId");
-
- if (!teamId && currentTeam) {
- setCurrentTeam(null);
- }
- };
-
- window.addEventListener("popstate", handleLocationChange);
- return () => window.removeEventListener("popstate", handleLocationChange);
- }, [currentTeam]);
-
const handleSelectTeam = async (selectedTeam: Team) => {
if (!user?.email || !selectedTeam.id) return;
@@ -87,14 +81,12 @@ export const TeamManager: React.FC = () => {
onOk: () => {
switchToTeam(selectedTeam.id);
},
- // onCancel - do nothing, user stays on current team
});
} else {
await switchToTeam(selectedTeam.id);
}
};
- // Modify switchToTeam to take the id directly
const switchToTeam = async (teamId: number | undefined) => {
if (!teamId || !user?.email) return;
setIsLoading(true);
@@ -128,8 +120,6 @@ export const TeamManager: React.FC = () => {
const handleCreateTeam = (newTeam: Team) => {
setCurrentTeam(newTeam);
- // also save it to db
-
handleSaveTeam(newTeam);
};
@@ -139,18 +129,15 @@ export const TeamManager: React.FC = () => {
try {
const sanitizedTeamData = {
...teamData,
- created_at: undefined, // Remove these fields
- updated_at: undefined, // Let server handle timestamps
+ created_at: undefined,
+ updated_at: undefined,
};
- // console.log("teamData", sanitizedTeamData);
const savedTeam = await teamAPI.createTeam(sanitizedTeamData, user.email);
-
messageApi.success(
`Team ${teamData.id ? "updated" : "created"} successfully`
);
- // Update teams list
if (teamData.id) {
setTeams(teams.map((t) => (t.id === savedTeam.id ? savedTeam : t)));
if (currentTeam?.id === savedTeam.id) {
@@ -196,7 +183,7 @@ export const TeamManager: React.FC = () => {
<div className="p-4 pt-2">
{/* Breadcrumb */}
<div className="flex items-center gap-2 mb-4 text-sm">
- <span className="text-primary font-medium"> Teams</span>
+ <span className="text-primary font-medium">Teams</span>
{currentTeam && (
<>
<ChevronRight className="w-4 h-4 text-secondary" />
@@ -220,7 +207,7 @@ export const TeamManager: React.FC = () => {
onDirtyStateChange={setHasUnsavedChanges}
/>
) : (
- <div className="flex items-center justify-center h-[calc(100vh-190px)] text-secondary">
+ <div className="flex items-center justify-center h-[calc(100vh-190px)] text-secondary">
Select a team from the sidebar or create a new one
</div>
)}
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.tsx
index ea73f687b..0017b9676 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
@@ -1,5 +1,5 @@
-import React from "react";
-import { Button, Tooltip } from "antd";
+import React, { useState } from "react";
+import { Button, Tooltip, Select } from "antd";
import {
Bot,
Plus,
@@ -10,6 +10,7 @@ import {
GalleryHorizontalEnd,
InfoIcon,
RefreshCcw,
+ History,
} from "lucide-react";
import type { Team } from "../../types/datamodel";
import { getRelativeTimeString } from "../atoms";
@@ -38,16 +39,16 @@ export const TeamSidebar: React.FC<TeamSidebarProps> = ({
onDeleteTeam,
isLoading = false,
}) => {
- const defaultGallery = useGalleryStore((state) => state.getDefaultGallery());
- const createTeam = () => {
- const newTeam = Object.assign(
- {},
- { component: defaultGallery?.components.teams[0] }
- );
- newTeam.component.label =
- "default_team" + new Date().getTime().toString().slice(0, 2);
- onCreateTeam(newTeam);
- };
+ // Tab state - "recent" or "gallery"
+ const [activeTab, setActiveTab] = useState<"recent" | "gallery">("recent");
+
+ // Gallery store
+ const {
+ galleries,
+ selectedGallery,
+ selectGallery,
+ isLoading: isLoadingGalleries,
+ } = useGalleryStore();
// Render collapsed state
if (!isOpen) {
@@ -69,7 +70,7 @@ export const TeamSidebar: React.FC<TeamSidebarProps> = ({
<Button
type="text"
className="w-full p-2 flex justify-center"
- onClick={createTeam}
+ onClick={() => createTeam()}
icon={<Plus className="w-4 h-4" />}
/>
</Tooltip>
@@ -78,6 +79,19 @@ export const TeamSidebar: React.FC<TeamSidebarProps> = ({
);
}
+ const createTeam = () => {
+ if (!selectedGallery?.config.components?.teams?.length) {
+ return;
+ }
+ const newTeam = Object.assign(
+ {},
+ { component: selectedGallery.config.components.teams[0] }
+ );
+ newTeam.component.label =
+ "default_team" + new Date().getTime().toString().slice(0, 2);
+ onCreateTeam(newTeam);
+ };
+
// Render expanded state
return (
<div className="h-full border-r border-secondary">
@@ -100,15 +114,15 @@ export const TeamSidebar: React.FC<TeamSidebarProps> = ({
</div>
{/* Create Team Button */}
-
- <div className="my-4 flex text-sm ">
- <div className=" mr-2 w-full">
+ <div className="my-4 flex text-sm">
+ <div className="mr-2 w-full">
<Tooltip title="Create a new team">
<Button
type="primary"
className="w-full"
icon={<Plus className="w-4 h-4" />}
onClick={createTeam}
+ disabled={!selectedGallery?.config.components?.teams?.length}
>
New Team
</Button>
@@ -116,129 +130,150 @@ export const TeamSidebar: React.FC<TeamSidebarProps> = ({
</div>
</div>
- {/* Section Label */}
- <div className="py-2 flex text-sm text-secondary">
- <div className="flex"> Recents</div>
- {isLoading && <RefreshCcw className="w-4 h-4 ml-2 animate-spin" />}
+ {/* Tab Navigation */}
+ <div className="flex border-b border-secondary">
+ <button
+ className={`flex items-center px-2 py-1 text-sm font-medium ${
+ activeTab === "recent"
+ ? "text-accent border-b-2 border-accent"
+ : "text-secondary hover:text-primary"
+ }`}
+ onClick={() => setActiveTab("recent")}
+ >
+ <History className="w-4 h-4 mr-1.5" />
+ Recents
+ <span className="ml-1 text-xs">({teams.length})</span>
+ {isLoading && activeTab === "recent" && (
+ <RefreshCcw className="w-4 h-4 ml-2 animate-spin" />
+ )}
+ </button>
+ <button
+ className={`flex items-center px-4 py-2 text-sm font-medium ${
+ activeTab === "gallery"
+ ? "text-accent border-b-2 border-accent"
+ : "text-secondary hover:text-primary"
+ }`}
+ onClick={() => setActiveTab("gallery")}
+ >
+ <GalleryHorizontalEnd className="w-4 h-4 mr-1.5" />
+ Gallery
+ {isLoadingGalleries && activeTab === "gallery" && (
+ <RefreshCcw className="w-4 h-4 ml-2 animate-spin" />
+ )}
+ </button>
</div>
- {/* Teams List */}
-
- {!isLoading && teams.length === 0 && (
- <div className="p-2 mr-2 text-center text-secondary text-sm border border-dashed rounded ">
- <InfoIcon className="w-4 h-4 inline-block mr-1.5 -mt-0.5" />
- No recent teams found
- </div>
- )}
+ <div className="scroll overflow-y-auto h-[calc(100%-200px)]">
+ {/* Recents Tab Content */}
+ {activeTab === "recent" && (
+ <div className="pt-2">
+ {!isLoading && teams.length === 0 && (
+ <div className="p-2 mr-2 text-center text-secondary text-sm border border-dashed rounded">
+ <InfoIcon className="w-4 h-4 inline-block mr-1.5 -mt-0.5" />
+ No recent teams found
+ </div>
+ )}
- <div className="scroll overflow-y-auto h-[calc(100%-170px)]">
- <>
- {teams.length > 0 && (
- <div
- key={"teams_title"}
- className={` ${isLoading ? " pointer-events-none" : ""}`}
- >
- {" "}
- {teams.map((team) => (
- <div key={team.id} className="relative border-secondary">
- {
+ {teams.length > 0 && (
+ <div className={isLoading ? "pointer-events-none" : ""}>
+ {teams.map((team) => (
+ <div key={team.id} className="relative border-secondary">
<div
- className={` absolute top-1 left-0.5 z-50 h-[calc(100%-8px)]
- w-1 bg-opacity-80 rounded ${
- currentTeam?.id === team.id ? "bg-accent" : "bg-tertiary"
- }`}
- >
- {" "}
- </div>
- }
- <div
- className={`group ml-1 flex flex-col p-3 rounded-l cursor-pointer hover:bg-secondary ${
- currentTeam?.id === team.id
- ? "border-accent bg-secondary"
- : "border-transparent"
- }`}
- onClick={() => onSelectTeam(team)}
- >
- {/* Team Name and Actions Row */}
- <div className="flex items-center justify-between">
- <span className="font-medium truncate">
- {team.component?.label}
- </span>
- <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
- {/* <Tooltip title="Edit team">
- <Button
- type="text"
- size="small"
- className="p-0 min-w-[24px] h-6"
- icon={<Edit className="w-4 h-4" />}
- onClick={(e) => {
- e.stopPropagation();
- onEditTeam(team);
- }}
+ className={`absolute top-1 left-0.5 z-50 h-[calc(100%-8px)]
+ w-1 bg-opacity-80 rounded ${
+ currentTeam?.id === team.id
+ ? "bg-accent"
+ : "bg-tertiary"
+ }`}
/>
- </Tooltip> */}
- <Tooltip title="Delete team">
- <Button
- type="text"
- size="small"
- className="p-0 min-w-[24px] h-6"
- danger
- icon={<Trash2 className="w-4 h-4 text-red-500" />}
- onClick={(e) => {
- e.stopPropagation();
- if (team.id) onDeleteTeam(team.id);
- }}
- />
- </Tooltip>
+ <div
+ className={`group ml-1 flex flex-col p-3 rounded-l cursor-pointer hover:bg-secondary ${
+ currentTeam?.id === team.id
+ ? "border-accent bg-secondary"
+ : "border-transparent"
+ }`}
+ onClick={() => onSelectTeam(team)}
+ >
+ {/* Team Name and Actions Row */}
+ <div className="flex items-center justify-between">
+ <span className="font-medium truncate">
+ {team.component?.label}
+ </span>
+ <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
+ <Tooltip title="Delete team">
+ <Button
+ type="text"
+ size="small"
+ className="p-0 min-w-[24px] h-6"
+ danger
+ icon={<Trash2 className="w-4 h-4 text-red-500" />}
+ onClick={(e) => {
+ e.stopPropagation();
+ if (team.id) onDeleteTeam(team.id);
+ }}
+ />
+ </Tooltip>
+ </div>
</div>
- </div>
- {/* Team Metadata Row */}
- <div className="mt-1 flex items-center gap-2 text-xs text-secondary">
- <span className="bg-secondary/20 truncate rounded">
- {team.component.component_type}
- </span>
- <div className="flex items-center gap-1">
- <Bot className="w-3 h-3" />
- <span>
- {team.component.config.participants.length}{" "}
- {team.component.config.participants.length === 1
- ? "agent"
- : "agents"}
+ {/* Team Metadata Row */}
+ <div className="mt-1 flex items-center gap-2 text-xs text-secondary">
+ <span className="bg-secondary/20 truncate rounded">
+ {team.component.component_type}
</span>
+ <div className="flex items-center gap-1">
+ <Bot className="w-3 h-3" />
+ <span>
+ {team.component.config.participants.length}{" "}
+ {team.component.config.participants.length === 1
+ ? "agent"
+ : "agents"}
+ </span>
+ </div>
</div>
- </div>
- {/* Updated Timestamp */}
- {team.updated_at && (
- <div className="mt-1 flex items-center gap-1 text-xs text-secondary">
- {/* <Calendar className="w-3 h-3" /> */}
- <span>{getRelativeTimeString(team.updated_at)}</span>
- </div>
- )}
+ {/* Updated Timestamp */}
+ {team.updated_at && (
+ <div className="mt-1 flex items-center gap-1 text-xs text-secondary">
+ <span>{getRelativeTimeString(team.updated_at)}</span>
+ </div>
+ )}
+ </div>
</div>
- </div>
- ))}
- </div>
- )}
-
- {/* Gallery Teams Section */}
- <div
- key={"gallery_title"}
- className="py-2 text-sm text-secondary mt-4"
- >
- <GalleryHorizontalEnd className="w-4 h-4 inline-block mr-1.5" />
- From Gallery
+ ))}
+ </div>
+ )}
</div>
- <div key={"gallery_content"} className="scroll overflow-y-auto">
- {defaultGallery?.components.teams.map((galleryTeam) => (
+ )}
+
+ {/* Gallery Tab Content */}
+ {activeTab === "gallery" && (
+ <div className="p-2">
+ {/* Gallery Selector */}
+ <Select
+ className="w-full mb-4"
+ placeholder="Select gallery"
+ value={selectedGallery?.id}
+ onChange={(value) => {
+ const gallery = galleries.find((g) => g.id === value);
+ if (gallery) selectGallery(gallery);
+ }}
+ options={galleries.map((gallery) => ({
+ value: gallery.id,
+ label: gallery.config.name,
+ }))}
+ loading={isLoadingGalleries}
+ />
+
+ {/* Gallery Templates */}
+ {selectedGallery?.config.components?.teams.map((galleryTeam) => (
<div
key={galleryTeam.label + galleryTeam.component_type}
className="relative border-secondary"
>
<div
className={`absolute top-1 left-0.5 z-50 h-[calc(100%-8px)]
- w-1 bg-opacity-80 rounded bg-tertiary`}
+ w-1 bg-opacity-80 rounded bg-tertiary`}
/>
<div className="group ml-1 flex flex-col p-3 rounded-l cursor-pointer hover:bg-secondary">
{/* Team Name and Use Template Action */}
@@ -255,13 +290,15 @@ export const TeamSidebar: React.FC<TeamSidebarProps> = ({
icon={<Copy className="w-4 h-4" />}
onClick={(e) => {
e.stopPropagation();
- galleryTeam.label =
- galleryTeam.label +
- "_" +
- (new Date().getTime() + "").substring(0, 5);
- onCreateTeam({
- component: galleryTeam,
- });
+ const newTeam = {
+ component: {
+ ...galleryTeam,
+ label: `${galleryTeam.label}_${(
+ new Date().getTime() + ""
+ ).substring(0, 5)}`,
+ },
+ };
+ onCreateTeam(newTeam);
}}
/>
</Tooltip>
@@ -286,9 +323,18 @@ export const TeamSidebar: React.FC<TeamSidebarProps> = ({
</div>
</div>
))}
+
+ {!selectedGallery && (
+ <div className="p-2 mr-2 text-center text-secondary text-sm border border-dashed rounded">
+ <InfoIcon className="w-4 h-4 inline-block mr-1.5 -mt-0.5" />
+ Select a gallery to view templates
+ </div>
+ )}
</div>
- </>
+ )}
</div>
</div>
);
};
+
+export default TeamSidebar;
diff --git a/python/packages/autogen-studio/frontend/yarn.lock b/python/packages/autogen-studio/frontend/yarn.lock
index 1b285da82..c5bfcf195 100644
--- a/python/packages/autogen-studio/frontend/yarn.lock
+++ b/python/packages/autogen-studio/frontend/yarn.lock
@@ -5275,6 +5275,11 @@ escape-string-regexp@^4.0.0:
resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz#14ba83a5d373e3d311e5afca29cf5bfad965bf34"
integrity sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==
+escape-string-regexp@^5.0.0:
+ version "5.0.0"
+ resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz#4683126b500b61762f2dbebace1806e8be31b1c8"
+ integrity sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==
+
eslint-config-react-app@^6.0.0:
version "6.0.0"
resolved "https://registry.yarnpkg.com/eslint-config-react-app/-/eslint-config-react-app-6.0.0.tgz#ccff9fc8e36b322902844cbd79197982be355a0e"
@@ -8173,6 +8178,11 @@ markdown-extensions@^1.0.0:
resolved "https://registry.yarnpkg.com/markdown-extensions/-/markdown-extensions-1.1.1.tgz#fea03b539faeaee9b4ef02a3769b455b189f7fc3"
integrity sha512-WWC0ZuMzCyDHYCasEGs4IPvLyTGftYwh6wIEOULOF0HXcqZlhwRzrK0w2VUlxWA98xnvb/jszw4ZSkJ6ADpM6Q==
+markdown-table@^3.0.0:
+ version "3.0.4"
+ resolved "https://registry.yarnpkg.com/markdown-table/-/markdown-table-3.0.4.tgz#fe44d6d410ff9d6f2ea1797a3f60aa4d2b631c2a"
+ integrity sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==
+
math-intrinsics@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/math-intrinsics/-/math-intrinsics-1.1.0.tgz#a0dd74be81e2aa5c2f27e65ce283605ee4e2b7f9"
@@ -8194,6 +8204,16 @@ mdast-util-definitions@^5.0.0:
"@types/unist" "^2.0.0"
unist-util-visit "^4.0.0"
+mdast-util-find-and-replace@^3.0.0:
+ version "3.0.2"
+ resolved "https://registry.yarnpkg.com/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.2.tgz#70a3174c894e14df722abf43bc250cbae44b11df"
+ integrity sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==
+ dependencies:
+ "@types/mdast" "^4.0.0"
+ escape-string-regexp "^5.0.0"
+ unist-util-is "^6.0.0"
+ unist-util-visit-parents "^6.0.0"
+
mdast-util-from-markdown@^1.0.0, mdast-util-from-markdown@^1.1.0:
version "1.3.1"
resolved "https://registry.yarnpkg.com/mdast-util-from-markdown/-/mdast-util-from-markdown-1.3.1.tgz#9421a5a247f10d31d2faed2a30df5ec89ceafcf0"
@@ -8230,6 +8250,71 @@ mdast-util-from-markdown@^2.0.0:
micromark-util-types "^2.0.0"
unist-util-stringify-position "^4.0.0"
+mdast-util-gfm-autolink-literal@^2.0.0:
+ version "2.0.1"
+ resolved "https://registry.yarnpkg.com/mdast-util-gfm-autolink-literal/-/mdast-util-gfm-autolink-literal-2.0.1.tgz#abd557630337bd30a6d5a4bd8252e1c2dc0875d5"
+ integrity sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ==
+ dependencies:
+ "@types/mdast" "^4.0.0"
+ ccount "^2.0.0"
+ devlop "^1.0.0"
+ mdast-util-find-and-replace "^3.0.0"
+ micromark-util-character "^2.0.0"
+
+mdast-util-gfm-footnote@^2.0.0:
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/mdast-util-gfm-footnote/-/mdast-util-gfm-footnote-2.1.0.tgz#7778e9d9ca3df7238cc2bd3fa2b1bf6a65b19403"
+ integrity sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ==
+ dependencies:
+ "@types/mdast" "^4.0.0"
+ devlop "^1.1.0"
+ mdast-util-from-markdown "^2.0.0"
+ mdast-util-to-markdown "^2.0.0"
+ micromark-util-normalize-identifier "^2.0.0"
+
+mdast-util-gfm-strikethrough@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/mdast-util-gfm-strikethrough/-/mdast-util-gfm-strikethrough-2.0.0.tgz#d44ef9e8ed283ac8c1165ab0d0dfd058c2764c16"
+ integrity sha512-mKKb915TF+OC5ptj5bJ7WFRPdYtuHv0yTRxK2tJvi+BDqbkiG7h7u/9SI89nRAYcmap2xHQL9D+QG/6wSrTtXg==
+ dependencies:
+ "@types/mdast" "^4.0.0"
+ mdast-util-from-markdown "^2.0.0"
+ mdast-util-to-markdown "^2.0.0"
+
+mdast-util-gfm-table@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/mdast-util-gfm-table/-/mdast-util-gfm-table-2.0.0.tgz#7a435fb6223a72b0862b33afbd712b6dae878d38"
+ integrity sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg==
+ dependencies:
+ "@types/mdast" "^4.0.0"
+ devlop "^1.0.0"
+ markdown-table "^3.0.0"
+ mdast-util-from-markdown "^2.0.0"
+ mdast-util-to-markdown "^2.0.0"
+
+mdast-util-gfm-task-list-item@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/mdast-util-gfm-task-list-item/-/mdast-util-gfm-task-list-item-2.0.0.tgz#e68095d2f8a4303ef24094ab642e1047b991a936"
+ integrity sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ==
+ dependencies:
+ "@types/mdast" "^4.0.0"
+ devlop "^1.0.0"
+ mdast-util-from-markdown "^2.0.0"
+ mdast-util-to-markdown "^2.0.0"
+
+mdast-util-gfm@^3.0.0:
+ version "3.1.0"
+ resolved "https://registry.yarnpkg.com/mdast-util-gfm/-/mdast-util-gfm-3.1.0.tgz#2cdf63b92c2a331406b0fb0db4c077c1b0331751"
+ integrity sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==
+ dependencies:
+ mdast-util-from-markdown "^2.0.0"
+ mdast-util-gfm-autolink-literal "^2.0.0"
+ mdast-util-gfm-footnote "^2.0.0"
+ mdast-util-gfm-strikethrough "^2.0.0"
+ mdast-util-gfm-table "^2.0.0"
+ mdast-util-gfm-task-list-item "^2.0.0"
+ mdast-util-to-markdown "^2.0.0"
+
mdast-util-mdx-expression@^1.0.0:
version "1.3.2"
resolved "https://registry.yarnpkg.com/mdast-util-mdx-expression/-/mdast-util-mdx-expression-1.3.2.tgz#d027789e67524d541d6de543f36d51ae2586f220"
@@ -8543,6 +8628,85 @@ micromark-core-commonmark@^2.0.0:
micromark-util-symbol "^2.0.0"
micromark-util-types "^2.0.0"
+micromark-extension-gfm-autolink-literal@^2.0.0:
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/micromark-extension-gfm-autolink-literal/-/micromark-extension-gfm-autolink-literal-2.1.0.tgz#6286aee9686c4462c1e3552a9d505feddceeb935"
+ integrity sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==
+ dependencies:
+ micromark-util-character "^2.0.0"
+ micromark-util-sanitize-uri "^2.0.0"
+ micromark-util-symbol "^2.0.0"
+ micromark-util-types "^2.0.0"
+
+micromark-extension-gfm-footnote@^2.0.0:
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/micromark-extension-gfm-footnote/-/micromark-extension-gfm-footnote-2.1.0.tgz#4dab56d4e398b9853f6fe4efac4fc9361f3e0750"
+ integrity sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw==
+ dependencies:
+ devlop "^1.0.0"
+ micromark-core-commonmark "^2.0.0"
+ micromark-factory-space "^2.0.0"
+ micromark-util-character "^2.0.0"
+ micromark-util-normalize-identifier "^2.0.0"
+ micromark-util-sanitize-uri "^2.0.0"
+ micromark-util-symbol "^2.0.0"
+ micromark-util-types "^2.0.0"
+
+micromark-extension-gfm-strikethrough@^2.0.0:
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/micromark-extension-gfm-strikethrough/-/micromark-extension-gfm-strikethrough-2.1.0.tgz#86106df8b3a692b5f6a92280d3879be6be46d923"
+ integrity sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw==
+ dependencies:
+ devlop "^1.0.0"
+ micromark-util-chunked "^2.0.0"
+ micromark-util-classify-character "^2.0.0"
+ micromark-util-resolve-all "^2.0.0"
+ micromark-util-symbol "^2.0.0"
+ micromark-util-types "^2.0.0"
+
+micromark-extension-gfm-table@^2.0.0:
+ version "2.1.1"
+ resolved "https://registry.yarnpkg.com/micromark-extension-gfm-table/-/micromark-extension-gfm-table-2.1.1.tgz#fac70bcbf51fe65f5f44033118d39be8a9b5940b"
+ integrity sha512-t2OU/dXXioARrC6yWfJ4hqB7rct14e8f7m0cbI5hUmDyyIlwv5vEtooptH8INkbLzOatzKuVbQmAYcbWoyz6Dg==
+ dependencies:
+ devlop "^1.0.0"
+ micromark-factory-space "^2.0.0"
+ micromark-util-character "^2.0.0"
+ micromark-util-symbol "^2.0.0"
+ micromark-util-types "^2.0.0"
+
+micromark-extension-gfm-tagfilter@^2.0.0:
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/micromark-extension-gfm-tagfilter/-/micromark-extension-gfm-tagfilter-2.0.0.tgz#f26d8a7807b5985fba13cf61465b58ca5ff7dc57"
+ integrity sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg==
+ dependencies:
+ micromark-util-types "^2.0.0"
+
+micromark-extension-gfm-task-list-item@^2.0.0:
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/micromark-extension-gfm-task-list-item/-/micromark-extension-gfm-task-list-item-2.1.0.tgz#bcc34d805639829990ec175c3eea12bb5b781f2c"
+ integrity sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw==
+ dependencies:
+ devlop "^1.0.0"
+ micromark-factory-space "^2.0.0"
+ micromark-util-character "^2.0.0"
+ micromark-util-symbol "^2.0.0"
+ micromark-util-types "^2.0.0"
+
+micromark-extension-gfm@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/micromark-extension-gfm/-/micromark-extension-gfm-3.0.0.tgz#3e13376ab95dd7a5cfd0e29560dfe999657b3c5b"
+ integrity sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==
+ dependencies:
+ micromark-extension-gfm-autolink-literal "^2.0.0"
+ micromark-extension-gfm-footnote "^2.0.0"
+ micromark-extension-gfm-strikethrough "^2.0.0"
+ micromark-extension-gfm-table "^2.0.0"
+ micromark-extension-gfm-tagfilter "^2.0.0"
+ micromark-extension-gfm-task-list-item "^2.0.0"
+ micromark-util-combine-extensions "^2.0.0"
+ micromark-util-types "^2.0.0"
+
micromark-extension-mdx-expression@^1.0.0:
version "1.0.8"
resolved "https://registry.yarnpkg.com/micromark-extension-mdx-expression/-/micromark-extension-mdx-expression-1.0.8.tgz#5bc1f5fd90388e8293b3ef4f7c6f06c24aff6314"
@@ -10973,6 +11137,18 @@ [email protected]:
fbjs "^3.0.0"
invariant "^2.2.4"
+remark-gfm@^4.0.1:
+ version "4.0.1"
+ resolved "https://registry.yarnpkg.com/remark-gfm/-/remark-gfm-4.0.1.tgz#33227b2a74397670d357bf05c098eaf8513f0d6b"
+ integrity sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==
+ dependencies:
+ "@types/mdast" "^4.0.0"
+ mdast-util-gfm "^3.0.0"
+ micromark-extension-gfm "^3.0.0"
+ remark-parse "^11.0.0"
+ remark-stringify "^11.0.0"
+ unified "^11.0.0"
+
remark-mdx@^2.0.0:
version "2.3.0"
resolved "https://registry.yarnpkg.com/remark-mdx/-/remark-mdx-2.3.0.tgz#efe678025a8c2726681bde8bf111af4a93943db4"
@@ -11021,6 +11197,15 @@ remark-rehype@^11.0.0:
unified "^11.0.0"
vfile "^6.0.0"
+remark-stringify@^11.0.0:
+ version "11.0.0"
+ resolved "https://registry.yarnpkg.com/remark-stringify/-/remark-stringify-11.0.0.tgz#4c5b01dd711c269df1aaae11743eb7e2e7636fd3"
+ integrity sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==
+ dependencies:
+ "@types/mdast" "^4.0.0"
+ mdast-util-to-markdown "^2.0.0"
+ unified "^11.0.0"
+
remark-unwrap-images@^3.0.1:
version "3.0.1"
resolved "https://registry.yarnpkg.com/remark-unwrap-images/-/remark-unwrap-images-3.0.1.tgz#22a547baa8fa1e2c66c7d087ebd9cf829a74a255"
diff --git a/python/packages/autogen-studio/notebooks/team.json b/python/packages/autogen-studio/notebooks/team.json
index 5fb43ea26..bcd3d6696 100644
--- a/python/packages/autogen-studio/notebooks/team.json
+++ b/python/packages/autogen-studio/notebooks/team.json
@@ -1,32 +1,99 @@
{
- "name": "weather_team",
+ "provider": "autogen_agentchat.teams.RoundRobinGroupChat",
"component_type": "team",
- "participants": [
- {
- "name": "writing_agent",
- "component_type": "agent",
- "model_client": {
- "model": "gpt-4o-2024-08-06",
- "model_type": "OpenAIChatCompletionClient",
- "component_type": "model"
- },
- "tools": [
- {
- "name": "get_weather",
- "description": "Get the weather for a city",
- "content": "async def get_weather(city: str) -> str:\n return f\"The weather in {city} is 73 degrees and Sunny.\"",
- "tool_type": "PythonFunction",
- "component_type": "tool"
+ "version": 1,
+ "component_version": 1,
+ "description": "A single AssistantAgent (with a calculator tool) in a RoundRobinGroupChat team. ",
+ "label": "default_team17",
+ "config": {
+ "participants": [
+ {
+ "provider": "autogen_agentchat.agents.AssistantAgent",
+ "component_type": "agent",
+ "version": 1,
+ "component_version": 1,
+ "description": "An agent that provides assistance with tool use.",
+ "label": "AssistantAgent",
+ "config": {
+ "name": "assistant_agent",
+ "model_client": {
+ "provider": "autogen_ext.models.openai.OpenAIChatCompletionClient",
+ "component_type": "model",
+ "version": 1,
+ "component_version": 1,
+ "description": "Chat completion client for OpenAI hosted models.",
+ "label": "OpenAIChatCompletionClient",
+ "config": {
+ "model": "gpt-4o-mini"
+ }
+ },
+ "tools": [
+ {
+ "provider": "autogen_core.tools.FunctionTool",
+ "component_type": "tool",
+ "version": 1,
+ "component_version": 1,
+ "description": "Create custom tools by wrapping standard Python functions.",
+ "label": "FunctionTool",
+ "config": {
+ "source_code": "def calculator(a: float, b: float, operator: str) -> str:\n try:\n if operator == \"+\":\n return str(a + b)\n elif operator == \"-\":\n return str(a - b)\n elif operator == \"*\":\n return str(a * b)\n elif operator == \"/\":\n if b == 0:\n return \"Error: Division by zero\"\n return str(a / b)\n else:\n return \"Error: Invalid operator. Please use +, -, *, or /\"\n except Exception as e:\n return f\"Error: {str(e)}\"\n",
+ "name": "calculator",
+ "description": "A simple calculator that performs basic arithmetic operations",
+ "global_imports": [],
+ "has_cancellation_support": false
+ }
+ }
+ ],
+ "handoffs": [],
+ "model_context": {
+ "provider": "autogen_core.model_context.UnboundedChatCompletionContext",
+ "component_type": "chat_completion_context",
+ "version": 1,
+ "component_version": 1,
+ "description": "An unbounded chat completion context that keeps a view of the all the messages.",
+ "label": "UnboundedChatCompletionContext",
+ "config": {}
+ },
+ "description": "An agent that provides assistance with ability to use tools.",
+ "system_message": "You are a helpful assistant. Solve tasks carefully. When done, say TERMINATE.",
+ "model_client_stream": false,
+ "reflect_on_tool_use": false,
+ "tool_call_summary_format": "{result}"
}
- ],
- "agent_type": "AssistantAgent"
+ }
+ ],
+ "termination_condition": {
+ "provider": "autogen_agentchat.base.OrTerminationCondition",
+ "component_type": "termination",
+ "version": 1,
+ "component_version": 1,
+ "label": "OrTerminationCondition",
+ "config": {
+ "conditions": [
+ {
+ "provider": "autogen_agentchat.conditions.TextMentionTermination",
+ "component_type": "termination",
+ "version": 1,
+ "component_version": 1,
+ "description": "Terminate the conversation if a specific text is mentioned.",
+ "label": "TextMentionTermination",
+ "config": {
+ "text": "TERMINATE"
+ }
+ },
+ {
+ "provider": "autogen_agentchat.conditions.MaxMessageTermination",
+ "component_type": "termination",
+ "version": 1,
+ "component_version": 1,
+ "description": "Terminate the conversation after a maximum number of messages have been exchanged.",
+ "label": "MaxMessageTermination",
+ "config": {
+ "max_messages": 10
+ }
+ }
+ ]
+ }
}
- ],
- "termination_condition": {
- "termination_type": "MaxMessageTermination",
- "max_messages": 5,
- "component_type": "termination"
- },
- "team_type": "RoundRobinGroupChat",
- "model_client": null
+ }
}
diff --git a/python/packages/autogen-studio/notebooks/tutorial.ipynb b/python/packages/autogen-studio/notebooks/tutorial.ipynb
index 8a267b52e..6b2633b80 100644
--- a/python/packages/autogen-studio/notebooks/tutorial.ipynb
+++ b/python/packages/autogen-studio/notebooks/tutorial.ipynb
@@ -59,6 +59,45 @@
" print(response)"
]
},
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Load Directly Using the AgentChat API "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[<autogen_agentchat.agents._assistant_agent.AssistantAgent object at 0x122b128d0>]\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "/Users/victordibia/projects/hax/autogen/python/packages/autogen-core/src/autogen_core/_component_config.py:252: UserWarning: \n",
+ "⚠️ SECURITY WARNING ⚠️\n",
+ "Loading a FunctionTool from config will execute code to import the provided global imports and and function code.\n",
+ "Only load configs from TRUSTED sources to prevent arbitrary code execution.\n",
+ " instance = component_class._from_config(validated_config) # type: ignore\n"
+ ]
+ }
+ ],
+ "source": [
+ "import json \n",
+ "from autogen_agentchat.teams import BaseGroupChat\n",
+ "team_config = json.load(open(\"team.json\")) \n",
+ "team = BaseGroupChat.load_component(team_config)\n",
+ "print(team._participants)"
+ ]
+ },
{
"cell_type": "markdown",
"metadata": {},