Instruction: Analyze this document content

Input:
# AutoGen Studio

[![PyPI version](https://badge.fury.io/py/autogenstudio.svg)](https://badge.fury.io/py/autogenstudio)
[![Downloads](https://static.pepy.tech/badge/autogenstudio/week)](https://pepy.tech/project/autogenstudio)

![ARA](./docs/ags_screen.png)

AutoGen Studio is an AutoGen-powered AI app (user interface) to help you rapidly prototype AI agents, enhance them with skills, compose them into workflows and interact with them to accomplish tasks. It is built on top of the [AutoGen](https://microsoft.github.io/autogen) framework, which is a toolkit for building AI agents.

Code for AutoGen Studio is on GitHub at [microsoft/autogen](https://github.com/microsoft/autogen/tree/main/python/packages/autogen-studio)

> **Note**: AutoGen Studio is meant to help you rapidly prototype multi-agent workflows and demonstrate an example of end user interfaces built with AutoGen. It is not meant to be a production-ready app.

> [!WARNING]
> AutoGen Studio is currently under active development

Output: Document summary and key points


Instruction: Analyze this code content

Input:
from setuptools import setup

setup()

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from .database.db_manager import DatabaseManager
from .datamodel import Agent, AgentConfig, Model, ModelConfig, Team, TeamConfig, Tool, ToolConfig
from .teammanager import TeamManager
from .version import __version__

__all__ = [
    "Tool",
    "Model",
    "DatabaseManager",
    "Team",
    "Agent",
    "ToolConfig",
    "ModelConfig",
    "TeamConfig",
    "AgentConfig",
    "TeamManager",
    "__version__",
]

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import os
from typing import Optional

import typer
import uvicorn
from typing_extensions import Annotated

from .version import VERSION

app = typer.Typer()

@app.command()
def ui(
    host: str = "127.0.0.1",
    port: int = 8081,
    workers: int = 1,
    reload: Annotated[bool, typer.Option("--reload")] = False,
    docs: bool = True,
    appdir: str = None,
    database_uri: Optional[str] = None,
    upgrade_database: bool = False,
):
    """
    Run the AutoGen Studio UI.

    Args:
        host (str, optional): Host to run the UI on. Defaults to 127.0.0.1 (localhost).
        port (int, optional): Port to run the UI on. Defaults to 8081.
        workers (int, optional): Number of workers to run the UI with. Defaults to 1.
        reload (bool, optional): Whether to reload the UI on code changes. Defaults to False.
        docs (bool, optional): Whether to generate API docs. Defaults to False.
        appdir (str, optional): Path to the AutoGen Studio app directory. Defaults to

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import time
from typing import AsyncGenerator, Callable, Optional, Union

from autogen_agentchat.base import TaskResult
from autogen_agentchat.messages import AgentEvent, ChatMessage
from autogen_core import CancellationToken

from .database import Component, ComponentFactory
from .datamodel import ComponentConfigInput, TeamResult

class TeamManager:
    def __init__(self) -> None:
        self.component_factory = ComponentFactory()

    async def _create_team(self, team_config: ComponentConfigInput, input_func: Optional[Callable] = None) -> Component:
        """Create team instance with common setup logic"""
        return await self.component_factory.load(team_config, input_func=input_func)

    def _create_result(self, task_result: TaskResult, start_time: float) -> TeamResult:
        """Create TeamResult with timing info"""
        return TeamResult(task_result=task_result, usage="", duration=time.time() - start_time)

    async def run_stream(
        self,
        task: str,

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
VERSION = "0.4.0.dev41"
__version__ = VERSION
APP_NAME = "autogenstudio"

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from .component_factory import Component, ComponentFactory
from .config_manager import ConfigurationManager
from .db_manager import DatabaseManager

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import json
import logging
from datetime import datetime
from pathlib import Path
from typing import Callable, Dict, List, Literal, Optional, Union

import aiofiles
import yaml
from autogen_agentchat.agents import AssistantAgent, UserProxyAgent
from autogen_agentchat.conditions import (
    ExternalTermination,
    HandoffTermination,
    MaxMessageTermination,
    SourceMatchTermination,
    StopMessageTermination,
    TextMentionTermination,
    TimeoutTermination,
    TokenUsageTermination,
)
from autogen_agentchat.teams import MagenticOneGroupChat, RoundRobinGroupChat, SelectorGroupChat
from autogen_core.tools import FunctionTool
from autogen_ext.agents.file_surfer import FileSurfer
from autogen_ext.agents.magentic_one import MagenticOneCoderAgent
from autogen_ext.agents.web_surfer import MultimodalWebSurfer
from autogen_ext.models.openai import AzureOpenAIChatCompletionClient, OpenAIChatCompletionClient

from ..datamodel.types import (
    AgentConfig,
    AgentTypes,
    Assistan

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import logging
from pathlib import Path
from typing import Any, Dict, List, Optional, Union

from loguru import logger

from ..datamodel.db import Agent, LinkTypes, Model, Team, Tool
from ..datamodel.types import ComponentConfigInput, ComponentTypes, Response
from .component_factory import ComponentFactory
from .db_manager import DatabaseManager

class ConfigurationManager:
    """Manages persistence and relationships of components using ComponentFactory for validation"""

    DEFAULT_UNIQUENESS_FIELDS = {
        ComponentTypes.MODEL: ["model_type", "model"],
        ComponentTypes.TOOL: ["name"],
        ComponentTypes.AGENT: ["agent_type", "name"],
        ComponentTypes.TEAM: ["team_type", "name"],
    }

    def __init__(self, db_manager: DatabaseManager, uniqueness_fields: Dict[ComponentTypes, List[str]] = None):
        self.db_manager = db_manager
        self.component_factory = ComponentFactory()
        self.uniqueness_fields = uniqueness_fields or self.DEFAULT_UNIQUENESS_F

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import threading
from datetime import datetime
from pathlib import Path
from typing import Optional

from loguru import logger
from sqlalchemy import exc, func, inspect, text
from sqlmodel import Session, SQLModel, and_, create_engine, select

from ..datamodel import LinkTypes, Response
from .schema_manager import SchemaManager

# from .dbutils import init_db_samples

class DatabaseManager:
    _init_lock = threading.Lock()

    def __init__(self, engine_uri: str, base_dir: Optional[Path] = None):
        """
        Initialize DatabaseManager with database connection settings.
        Does not perform any database operations.

        Args:
            engine_uri: Database connection URI (e.g. sqlite:///db.sqlite3)
            base_dir: Base directory for migration files. If None, uses current directory
        """
        connection_args = {"check_same_thread": True} if "sqlite" in engine_uri else {}

        self.engine = create_engine(engine_uri, connect_args=connection_args)

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import os
import shutil
from pathlib import Path
from typing import List, Optional, Tuple

import sqlmodel
from alembic import command
from alembic.autogenerate import compare_metadata
from alembic.config import Config
from alembic.runtime.migration import MigrationContext
from alembic.script import ScriptDirectory
from alembic.util.exc import CommandError
from loguru import logger
from sqlalchemy import Engine, text
from sqlmodel import SQLModel

class SchemaManager:
    """
    Manages database schema validation and migrations using Alembic.
    Operations are initiated explicitly by DatabaseManager.
    """

    def __init__(
        self,
        engine: Engine,
        base_dir: Optional[Path] = None,
    ):
        """
        Initialize configuration only - no filesystem or DB operations.

        Args:
            engine: SQLAlchemy engine instance
            base_dir: Base directory for Alembic files. If None, uses current working directory
        """
        # Convert stri

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from .db import Agent, LinkTypes, Message, Model, Run, RunStatus, Session, Team, Tool
from .types import (
    AgentConfig,
    ComponentConfigInput,
    MessageConfig,
    ModelConfig,
    Response,
    TeamConfig,
    TeamResult,
    ToolConfig,
)

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# defines how core data types in autogenstudio are serialized and stored in the database

from datetime import datetime
from enum import Enum
from typing import List, Optional, Tuple, Type, Union
from uuid import UUID, uuid4

from loguru import logger
from pydantic import BaseModel
from sqlalchemy import ForeignKey, Integer, UniqueConstraint
from sqlmodel import JSON, Column, DateTime, Field, Relationship, SQLModel, func

from .types import AgentConfig, MessageConfig, MessageMeta, ModelConfig, TeamConfig, TeamResult, ToolConfig

# added for python3.11 and sqlmodel 0.0.22 incompatibility
if hasattr(SQLModel, "model_config"):
    SQLModel.model_config["protected_namespaces"] = ()
elif hasattr(SQLModel, "Config"):

    class CustomSQLModel(SQLModel):
        class Config:
            protected_namespaces = ()

    SQLModel = CustomSQLModel
else:
    logger.warning("Unable to set protected_namespaces.")

# pylint: disable=protected-access

class ComponentTypes(Enum):
    TEAM = "team"

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from datetime import datetime
from enum import Enum
from pathlib import Path
from typing import Any, Dict, List, Optional, Union

from autogen_agentchat.base import TaskResult
from autogen_core.models import ModelCapabilities
from pydantic import BaseModel, Field

class ModelTypes(str, Enum):
    OPENAI = "OpenAIChatCompletionClient"
    AZUREOPENAI = "AzureOpenAIChatCompletionClient"

class ToolTypes(str, Enum):
    PYTHON_FUNCTION = "PythonFunction"

class AgentTypes(str, Enum):
    ASSISTANT = "AssistantAgent"
    USERPROXY = "UserProxyAgent"
    MULTIMODAL_WEBSURFER = "MultimodalWebSurfer"
    FILE_SURFER = "FileSurfer"
    MAGENTIC_ONE_CODER = "MagenticOneCoderAgent"

class TeamTypes(str, Enum):
    ROUND_ROBIN = "RoundRobinGroupChat"
    SELECTOR = "SelectorGroupChat"
    MAGENTIC_ONE = "MagenticOneGroupChat"

class TerminationTypes(str, Enum):
    MAX_MESSAGES = "MaxMessageTermination"
    STOP_MESSAGE = "StopMessageTermination"
    TEXT_MENTION = "TextMentionTermination"

Output: Code analysis and explanation


Instruction: Analyze this code content

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import base64
import hashlib
import os
import re
import shutil
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Tuple, Union

from dotenv import load_dotenv
from loguru import logger

from ..datamodel import Model
from ..version import APP_NAME

def sha256_hash(text: str) -> str:
    """
    Compute the MD5 hash of a given text.

    :param text: The string to hash
    :return: The MD5 hash of the text
    """
    return hashlib.sha256(text.encode()).hexdigest()

def check_and_cast_datetime_fields(obj: Any) -> Any:
    if hasattr(obj, "created_at") and isinstance(obj.created_at, str):
        obj.created_at = str_to_datetime(obj.created_at)

    if hasattr(obj, "updated_at") and isinstance(obj.updated_at, str):
        obj.updated_at = str_to_datetime(obj.updated_at)

    return obj

def str_to_datetime(dt_str: str) -> datetime:
    if dt_str[-1] == "Z":
        # Replace 'Z' with '+00:00' for UTC timezone
        dt_str = dt_str[:-1] + "+00

Output: Code analysis and explanation


Instruction: Analyze this code content

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# api/app.py
import os
from contextlib import asynccontextmanager
from typing import AsyncGenerator

# import logging
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from loguru import logger

from ..version import VERSION
from .config import settings
from .deps import cleanup_managers, init_managers
from .initialization import AppInitializer
from .routes import agents, models, runs, sessions, teams, tools, ws

# Configure logging
# logger = logging.getLogger(__name__)
# logging.basicConfig(level=logging.INFO)

# Initialize application
app_file_path = os.path.dirname(os.path.abspath(__file__))
initializer = AppInitializer(settings, app_file_path)

@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
    """
    Lifecycle manager for the FastAPI application.
    Handles initialization and cleanup of application resources.
    """
    # Startup
    logger.info("Initializing applic

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# api/config.py
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    DATABASE_URI: str = "sqlite:///./autogen.db"
    API_DOCS: bool = False
    CLEANUP_INTERVAL: int = 300  # 5 minutes
    SESSION_TIMEOUT: int = 3600  # 1 hour
    CONFIG_DIR: str = "configs"  # Default config directory relative to app_root
    DEFAULT_USER_ID: str = "guestuser@gmail.com"
    UPGRADE_DATABASE: bool = False

    class Config:
        env_prefix = "AUTOGENSTUDIO_"

settings = Settings()

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# api/deps.py
import logging
from contextlib import contextmanager
from typing import Optional

from fastapi import Depends, HTTPException, status

from ..database import ConfigurationManager, DatabaseManager
from ..teammanager import TeamManager
from .config import settings
from .managers.connection import WebSocketManager

logger = logging.getLogger(__name__)

# Global manager instances
_db_manager: Optional[DatabaseManager] = None
_websocket_manager: Optional[WebSocketManager] = None
_team_manager: Optional[TeamManager] = None

# Context manager for database sessions

@contextmanager
def get_db_context():
    """Provide a transactional scope around a series of operations."""
    if not _db_manager:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Database manager not initialized"
        )
    try:
        yield _db_manager
    except Exception as e:
        logger.error(f"Database operation failed: {str(e)}")
        raise HTTPExc

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# api/initialization.py
import os
from pathlib import Path
from typing import Dict

from dotenv import load_dotenv
from loguru import logger
from pydantic import BaseModel

from .config import Settings

class _AppPaths(BaseModel):
    """Internal model representing all application paths"""

    app_root: Path
    static_root: Path
    user_files: Path
    ui_root: Path
    config_dir: Path
    database_uri: str

class AppInitializer:
    """Handles application initialization including paths and environment setup"""

    def __init__(self, settings: Settings, app_path: str):
        """
        Initialize the application structure.

        Args:
            settings: Application settings
            app_path: Path to the application code directory
        """
        self.settings = settings
        self._app_path = Path(app_path)
        self._paths = self._init_paths()
        self._create_directories()
        self._load_environment()
        logger.info(f"Initialized application

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# loads a fast api api endpoint with a single endpoint that takes text query and return a response

import json
import os

from fastapi import FastAPI

from ..datamodel import Response
from ..teammanager import TeamManager

app = FastAPI()
team_file_path = os.environ.get("AUTOGENSTUDIO_TEAM_FILE", None)

if team_file_path:
    team_manager = TeamManager()
else:
    raise ValueError("Team file must be specified")

@app.get("/predict/{task}")
async def predict(task: str):
    response = Response(message="Task successfully completed", status=True, data=None)
    try:
        result_message = await team_manager.run(task=task, team_config=team_file_path)
        response.data = result_message
    except Exception as e:
        response.message = str(e)
        response.status = False
    return response

Output: Code analysis and explanation


Instruction: Analyze this code content

Input: from .connection import WebSocketManager

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import asyncio
import logging
from datetime import datetime, timezone
from typing import Any, Callable, Dict, Optional, Union
from uuid import UUID

from autogen_agentchat.base._task import TaskResult
from autogen_agentchat.messages import (
    AgentEvent,
    ChatMessage,
    HandoffMessage,
    MultiModalMessage,
    StopMessage,
    TextMessage,
    ToolCallExecutionEvent,
    ToolCallRequestEvent,
)
from autogen_core import CancellationToken
from autogen_core import Image as AGImage
from fastapi import WebSocket, WebSocketDisconnect

from ...database import DatabaseManager
from ...datamodel import Message, MessageConfig, Run, RunStatus, TeamResult
from ...teammanager import TeamManager

logger = logging.getLogger(__name__)

class WebSocketManager:
    """Manages WebSocket connections and message streaming for team task execution"""

    def __init__(self, db_manager: DatabaseManager):
        self.db_manager = db_manager
        self._connections: Dict[UUID, WebSocket] = {}

Output: Code analysis and explanation


Instruction: Analyze this code content

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from typing import Dict

from fastapi import APIRouter, Depends, HTTPException

from ...database import DatabaseManager  # Add this import
from ...datamodel import Agent, Model, Tool
from ..deps import get_db

router = APIRouter()

@router.get("/")
async def list_agents(user_id: str, db: DatabaseManager = Depends(get_db)) -> Dict:
    """List all agents for a user"""
    response = db.get(Agent, filters={"user_id": user_id})
    return {"status": True, "data": response.data}

@router.get("/{agent_id}")
async def get_agent(agent_id: int, user_id: str, db: DatabaseManager = Depends(get_db)) -> Dict:
    """Get a specific agent"""
    response = db.get(Agent, filters={"id": agent_id, "user_id": user_id})
    if not response.status or not response.data:
        raise HTTPException(status_code=404, detail="Agent not found")
    return {"status": True, "data": response.data[0]}

@router.post("/")
async def create_agent(agent: Agent, db: DatabaseManager = Depends(get_db)) -> Dict:
    """C

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# api/routes/gallery.py
from fastapi import APIRouter, Depends, HTTPException

from ...database import DatabaseManager
from ...datamodel import Gallery, GalleryConfig, Response, Run, Session
from ..deps import get_db

router = APIRouter()

@router.post("/")
async def create_gallery_entry(
    gallery_data: GalleryConfig, 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 ru

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# api/routes/models.py
from typing import Dict

from fastapi import APIRouter, Depends, HTTPException
from openai import OpenAIError

from ...datamodel import Model
from ..deps import get_db

router = APIRouter()

@router.get("/")
async def list_models(user_id: str, db=Depends(get_db)) -> Dict:
    """List all models for a user"""
    response = db.get(Model, filters={"user_id": user_id})
    return {"status": True, "data": response.data}

@router.get("/{model_id}")
async def get_model(model_id: int, user_id: str, db=Depends(get_db)) -> Dict:
    """Get a specific model"""
    response = db.get(Model, filters={"id": model_id, "user_id": user_id})
    if not response.status or not response.data:
        raise HTTPException(status_code=404, detail="Model not found")
    return {"status": True, "data": response.data[0]}

@router.post("/")
async def create_model(model: Model, db=Depends(get_db)) -> Dict:
    """Create a new model"""
    response = db.upsert(model)
    if not response.st

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# /api/runs routes
from typing import Dict
from uuid import UUID

from fastapi import APIRouter, Body, Depends, HTTPException
from pydantic import BaseModel

from ...datamodel import Message, MessageConfig, Run, RunStatus, Session, Team
from ..deps import get_db, get_team_manager, get_websocket_manager

router = APIRouter()

class CreateRunRequest(BaseModel):
    session_id: int
    user_id: str

@router.post("/")
async def create_run(
    request: CreateRunRequest,
    db=Depends(get_db),
) -> Dict:
    """Create a new run with initial state"""
    session_response = db.get(
        Session, filters={"id": request.session_id, "user_id": request.user_id}, return_json=False
    )
    if not session_response.status or not session_response.data:
        raise HTTPException(status_code=404, detail="Session not found")

    try:
        # Create run with default state
        run = db.upsert(
            Run(
                session_id=request.session_id,
                status=RunStatus.

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# api/routes/sessions.py
from typing import Dict

from fastapi import APIRouter, Depends, HTTPException
from loguru import logger

from ...datamodel import Message, Run, Session
from ..deps import get_db

router = APIRouter()

@router.get("/")
async def list_sessions(user_id: str, db=Depends(get_db)) -> Dict:
    """List all sessions for a user"""
    response = db.get(Session, filters={"user_id": user_id})
    return {"status": True, "data": response.data}

@router.get("/{session_id}")
async def get_session(session_id: int, user_id: str, db=Depends(get_db)) -> Dict:
    """Get a specific session"""
    response = db.get(Session, filters={"id": session_id, "user_id": user_id})
    if not response.status or not response.data:
        raise HTTPException(status_code=404, detail="Session not found")
    return {"status": True, "data": response.data[0]}

@router.post("/")
async def create_session(session: Session, db=Depends(get_db)) -> Dict:
    """Create a new session"""
    response

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# api/routes/teams.py
from typing import Dict

from fastapi import APIRouter, Depends, HTTPException

from ...datamodel import Team
from ..deps import get_db

router = APIRouter()

@router.get("/")
async def list_teams(user_id: str, db=Depends(get_db)) -> Dict:
    """List all teams for a user"""
    response = db.get(Team, filters={"user_id": user_id})
    return {"status": True, "data": response.data}

@router.get("/{team_id}")
async def get_team(team_id: int, user_id: str, db=Depends(get_db)) -> Dict:
    """Get a specific team"""
    response = db.get(Team, filters={"id": team_id, "user_id": user_id})
    if not response.status or not response.data:
        raise HTTPException(status_code=404, detail="Team not found")
    return {"status": True, "data": response.data[0]}

@router.post("/")
async def create_team(team: Team, db=Depends(get_db)) -> Dict:
    """Create a new team"""
    response = db.upsert(team)
    if not response.status:
        raise HTTPException(status_code=40

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# api/routes/tools.py
from typing import Dict

from fastapi import APIRouter, Depends, HTTPException

from ...datamodel import Tool
from ..deps import get_db

router = APIRouter()

@router.get("/")
async def list_tools(user_id: str, db=Depends(get_db)) -> Dict:
    """List all tools for a user"""
    response = db.get(Tool, filters={"user_id": user_id})
    return {"status": True, "data": response.data}

@router.get("/{tool_id}")
async def get_tool(tool_id: int, user_id: str, db=Depends(get_db)) -> Dict:
    """Get a specific tool"""
    response = db.get(Tool, filters={"id": tool_id, "user_id": user_id})
    if not response.status or not response.data:
        raise HTTPException(status_code=404, detail="Tool not found")
    return {"status": True, "data": response.data[0]}

@router.post("/")
async def create_tool(tool: Tool, db=Depends(get_db)) -> Dict:
    """Create a new tool"""
    response = db.upsert(tool)
    if not response.status:
        raise HTTPException(status_code=40

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# api/ws.py
import asyncio
import json
from datetime import datetime
from uuid import UUID

from fastapi import APIRouter, Depends, WebSocket, WebSocketDisconnect
from loguru import logger

from ...datamodel import Run, RunStatus
from ..deps import get_db, get_websocket_manager
from ..managers import WebSocketManager

router = APIRouter()

@router.websocket("/runs/{run_id}")
async def run_websocket(
    websocket: WebSocket,
    run_id: UUID,
    ws_manager: WebSocketManager = Depends(get_websocket_manager),
    db=Depends(get_db),
):
    """WebSocket endpoint for run communication"""
    # Verify run exists and is in valid state
    run_response = db.get(Run, filters={"id": run_id}, return_json=False)
    if not run_response.status or not run_response.data:
        logger.warning(f"Run not found: {run_id}")
        await websocket.close(code=4004, reason="Run not found")
        return

    run = run_response.data[0]
    if run.status not in [RunStatus.CREATED, RunStatus.ACTIVE]:

Output: Code analysis and explanation


Instruction: Analyze this document content

Input:
## 🚀 Running UI in Dev Mode

Run the UI in dev mode (make changes and see them reflected in the browser with hotreloading):

- yarn install
- yarn start

This should start the server on port 8000.

## Design Elements

- **Gatsby**: The app is created in Gatsby. A guide on bootstrapping a Gatsby app can be found here - https://www.gatsbyjs.com/docs/quick-start/.
  This provides an overview of the project file structure include functionality of files like `gatsby-config.js`, `gatsby-node.js`, `gatsby-browser.js` and `gatsby-ssr.js`.
- **TailwindCSS**: The app uses TailwindCSS for styling. A guide on using TailwindCSS with Gatsby can be found here - https://tailwindcss.com/docs/guides/gatsby.https://tailwindcss.com/docs/guides/gatsby . This will explain the functionality in tailwind.config.js and postcss.config.js.

## Modifying the UI, Adding Pages

The core of the app can be found in the `src` folder. To add pages, add a new folder in `src/pages` and add a `index.js` file. This will be

Output: Document summary and key points


Instruction: Analyze this code content

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import pytest
from typing import List

from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import RoundRobinGroupChat, SelectorGroupChat, MagenticOneGroupChat
from autogen_agentchat.conditions import MaxMessageTermination, StopMessageTermination, TextMentionTermination
from autogen_core.tools import FunctionTool

from autogenstudio.datamodel.types import (
    AssistantAgentConfig,
    OpenAIModelConfig,
    RoundRobinTeamConfig,
    SelectorTeamConfig,
    MagenticOneTeamConfig,
    ToolConfig,
    MaxMessageTerminationConfig,
    StopMessageTerminationConfig,
    TextMentionTerminationConfig,
    CombinationTerminationConfig,
    ModelTypes,
    AgentTypes,
    TeamTypes,
    TerminationTypes,
    ToolTypes,
    ComponentTypes,
)
from autogenstudio.database import ComponentFactory

@pytest.fixture
def component_factory():
    return ComponentFactory()

@pytest.fixture
def sample_tool_config():
    return ToolConfig(
        name="calculator",
        de

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import os
import asyncio
import pytest
from sqlmodel import Session, text, select
from typing import Generator

from autogenstudio.database import DatabaseManager
from autogenstudio.datamodel.types import (
    ToolConfig,
    OpenAIModelConfig,
    RoundRobinTeamConfig,
    StopMessageTerminationConfig,
    AssistantAgentConfig,
    ModelTypes, AgentTypes, TeamTypes, ComponentTypes,
    TerminationTypes,  ToolTypes
)
from autogenstudio.datamodel.db import Model, Tool, Agent, Team, LinkTypes

@pytest.fixture
def test_db() -> Generator[DatabaseManager, None, None]:
    """Fixture for test database"""
    db_path = "test.db"
    db = DatabaseManager(f"sqlite:///{db_path}")
    db.reset_db()
    # Initialize database instead of create_db_and_tables
    db.initialize_database(auto_upgrade=False)
    yield db
    # Clean up
    asyncio.run(db.close())
    db.reset_db()
    try:
        if os.path.exists(db_path):
            os.remove(db_path)
    except Exception as e:
        print(f"War

Output: Code analysis and explanation


Instruction: Analyze this document content

Input: # test-utils

Output: Document summary and key points


Instruction: Analyze this code content

Input:
from __future__ import annotations

from dataclasses import dataclass
from typing import Any

from autogen_core import (
    BaseAgent,
    Component,
    DefaultTopicId,
    MessageContext,
    RoutedAgent,
    default_subscription,
    message_handler,
)
from autogen_core._component_config import ComponentModel
from pydantic import BaseModel

@dataclass
class MessageType: ...

@dataclass
class CascadingMessageType:
    round: int

@dataclass
class ContentMessage:
    content: str

class LoopbackAgent(RoutedAgent):
    def __init__(self) -> None:
        super().__init__("A loop back agent.")
        self.num_calls = 0
        self.received_messages: list[Any] = []

    @message_handler
    async def on_new_message(
        self, message: MessageType | ContentMessage, ctx: MessageContext
    ) -> MessageType | ContentMessage:
        self.num_calls += 1
        self.received_messages.append(message)
        return message

@default_subscription
class LoopbackAgentWithDefaultSubsc

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from typing import List, Sequence

import pytest
from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor, SpanExporter, SpanExportResult

class MyTestExporter(SpanExporter):
    def __init__(self) -> None:
        self.exported_spans: List[ReadableSpan] = []

    def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
        self.exported_spans.extend(spans)
        return SpanExportResult.SUCCESS

    def shutdown(self) -> None:
        pass

    def clear(self) -> None:
        """Clears the list of exported spans."""
        self.exported_spans.clear()

    def get_exported_spans(self) -> List[ReadableSpan]:
        """Returns the list of exported spans."""
        return self.exported_spans

def get_test_tracer_provider(exporter: MyTestExporter) -> TracerProvider:
    tracer_provider = TracerProvider()
    tracer_provider.add_span_processor(SimpleSpanProcessor(exporter))
    return tracer_provid

Output: Code analysis and explanation


Instruction: Analyze this document content

Input:
# component-schema-gen

This is a tool to generate schema for built in components.

Simply run `gen-component-schema` and it will print the schema to be used.

Output: Document summary and key points


Instruction: Analyze this code content

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import json
import sys
from typing import Any, DefaultDict, Dict, List, TypeVar

from autogen_core import ComponentModel
from autogen_core._component_config import (
    WELL_KNOWN_PROVIDERS,
    ComponentConfigImpl,
    _type_to_provider_str,  # type: ignore
)
from autogen_ext.models.openai import AzureOpenAIChatCompletionClient, AzureTokenProvider, OpenAIChatCompletionClient
from pydantic import BaseModel

all_defs: Dict[str, Any] = {}

T = TypeVar("T", bound=BaseModel)

def build_specific_component_schema(component: type[ComponentConfigImpl[T]], provider_str: str) -> Dict[str, Any]:
    model = component.component_config_schema  # type: ignore
    model_schema = model.model_json_schema()

    component_model_schema = ComponentModel.model_json_schema()
    if "$defs" not in component_model_schema:
        component_model_schema["$defs"] = {}

    if "$defs" not in model_schema:
        model_schema["$defs"] = {}
    component_model_schema["$defs"].update(model_schema["$defs"])  # ty

Output: Code analysis and explanation


Instruction: Analyze this document content

Input:
# Building a Multi-Agent Application with AutoGen and Chainlit

In this sample, we will build a simple chat interface that interacts with a `RoundRobinGroupChat` team built using the [AutoGen AgentChat](https://microsoft.github.io/autogen/dev/user-guide/agentchat-user-guide/index.html) api.

![AgentChat](docs/chainlit_autogen.png).

## High-Level Description

The `app.py` script sets up a Chainlit chat interface that communicates with the AutoGen team. When a chat starts, it

- Initializes an AgentChat team.

```python

async def get_weather(city: str) -> str:
    return f"The weather in {city} is 73 degrees and Sunny."

assistant_agent = AssistantAgent(
    name="assistant_agent",
    tools=[get_weather],
    model_client=OpenAIChatCompletionClient(
        model="gpt-4o-2024-08-06"))

termination = TextMentionTermination("TERMINATE") | MaxMessageTermination(10)
team = RoundRobinGroupChat(
    participants=[assistant_agent], termination_condition=termination)

```

- As users interac

Output: Document summary and key points


Instruction: Analyze this code content

Input:
import chainlit as cl
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.conditions import TextMentionTermination, MaxMessageTermination
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_agentchat.base import TaskResult

async def get_weather(city: str) -> str:
    return f"The weather in {city} is 73 degrees and Sunny."

@cl.on_chat_start
async def start_chat():
    cl.user_session.set(
        "prompt_history",
        "",
    )

async def run_team(query: str):
    assistant_agent = AssistantAgent(
        name="assistant_agent", tools=[get_weather], model_client=OpenAIChatCompletionClient(model="gpt-4o-2024-08-06")
    )

    termination = TextMentionTermination("TERMINATE") | MaxMessageTermination(10)
    team = RoundRobinGroupChat(participants=[assistant_agent], termination_condition=termination)

    response_stream = team.run_stream(task=query)
    async for msg in resp

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import os
import shutil
from pathlib import Path
import tomli_w
import tomllib

source_dir = os.getcwd()
target_dir = "{{ cookiecutter.__final_destination }}"

shutil.move(source_dir, target_dir)

THIS_FILE_DIR = Path(__file__).parent

# Add the package to the workspace def

workspace_def_path = THIS_FILE_DIR / ".." / ".." / ".." / "pyproject.toml"

with workspace_def_path.open("rb") as f:
    config = tomllib.load(f)

config["tool"]["uv"]["sources"]["{{ cookiecutter.package_name }}"] = {"workspace": True}

with workspace_def_path.open("wb") as f:
    tomli_w.dump(config, f)

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import re
import sys
from packaging import version

MODULE_REGEX = r"^[a-zA-Z][\-a-zA-Z0-9]+$"

package_name = "{{ cookiecutter.package_name }}"

at_least_one_error = False
if not re.match(MODULE_REGEX, package_name):
    print(f'ERROR: "{package_name}" must use kebab case')
    at_least_one_error = True

packaging_version = "{{ cookiecutter.version }}"

# Check version format using version.VERSION_PATTERN
if not re.match(version.VERSION_PATTERN, packaging_version, re.VERBOSE | re.IGNORECASE):
    print(f'ERROR: "{packaging_version}" is not a valid version string')
    at_least_one_error = True

if at_least_one_error:
    sys.exit(1)

Output: Code analysis and explanation


Instruction: Analyze this document content

Input: # {{cookiecutter.package_name}}

Output: Document summary and key points


Instruction: Analyze this code content

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
async def test_example() -> None:
    assert True

Output: Code analysis and explanation