instruction
stringclasses
2 values
input
stringlengths
0
1k
output
stringclasses
2 values
metadata
dict
Analyze this code content
"""This example demonstrates a human user interacting with a web surfer agent to navigate the web through an embedded incognito browser. The human user and the web surfer agent takes turn to write input or perform actions, orchestrated by an round-robin orchestrator agent.""" import asyncio import logging import os from autogen_core import EVENT_LOGGER_NAME, AgentId, AgentProxy, SingleThreadedAgentRuntime from autogen_magentic_one.agents.multimodal_web_surfer import MultimodalWebSurfer from autogen_magentic_one.agents.orchestrator import RoundRobinOrchestrator from autogen_magentic_one.agents.user_proxy import UserProxy from autogen_magentic_one.messages import RequestReplyMessage from autogen_magentic_one.utils import LogHandler, create_completion_client_from_env # NOTE: Don't forget to 'playwright install --with-deps chromium' async def main() -> None: # Create the runtime. runtime = SingleThreadedAgentRuntime() # Create an appropriate client client = create_com
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/examples/example_websurfer.py", "file_type": ".py", "source_type": "code" }
Analyze this document content
# MagenticOne Interface This repository contains a preview interface for interacting with the MagenticOne system. It includes helper classes, and example usage. ## Usage ### MagenticOneHelper The MagenticOneHelper class provides an interface to interact with the MagenticOne system. It saves logs to a user-specified directory and provides methods to run tasks, stream logs, and retrieve the final answer. The class provides the following methods: - async initialize(self) -> None: Initializes the MagenticOne system, setting up agents and runtime. - async run_task(self, task: str) -> None: Runs a specific task through the MagenticOne system. - get_final_answer(self) -> Optional[str]: Retrieves the final answer from the Orchestrator. - async stream_logs(self) -> AsyncGenerator[Dict[str, Any], None]: Streams logs from the system as they are generated. - get_all_logs(self) -> List[Dict[str, Any]]: Retrieves all logs that have been collected so far. We show an example of how to use the M
Document summary and key points
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/interface/README.md", "file_type": ".md", "source_type": "document" }
Analyze this code content
from magentic_one_helper import MagenticOneHelper import asyncio import json import argparse import os async def main(task, logs_dir): magnetic_one = MagenticOneHelper(logs_dir=logs_dir) await magnetic_one.initialize() print("MagenticOne initialized.") # Create task and log streaming tasks task_future = asyncio.create_task(magnetic_one.run_task(task)) final_answer = None # Stream and process logs async for log_entry in magnetic_one.stream_logs(): print(json.dumps(log_entry, indent=2)) # Wait for task to complete await task_future # Get the final answer final_answer = magnetic_one.get_final_answer() if final_answer is not None: print(f"Final answer: {final_answer}") else: print("No final answer found in logs.") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run a task with MagenticOneHelper.") parser.add_argument("task", type=str, help="The task to run") parser.
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/interface/example_magentic_one_helper.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
import asyncio import logging import os from typing import Optional, AsyncGenerator, Dict, Any, List from datetime import datetime import json from dataclasses import asdict from autogen_core import SingleThreadedAgentRuntime from autogen_core import EVENT_LOGGER_NAME from autogen_core import AgentId, AgentProxy from autogen_core import DefaultTopicId from autogen_ext.code_executors.local import LocalCommandLineCodeExecutor from autogen_ext.code_executors.docker import DockerCommandLineCodeExecutor from autogen_core.code_executor import CodeBlock from autogen_magentic_one.agents.coder import Coder, Executor from autogen_magentic_one.agents.file_surfer import FileSurfer from autogen_magentic_one.agents.multimodal_web_surfer import MultimodalWebSurfer from autogen_magentic_one.agents.orchestrator import LedgerOrchestrator from autogen_magentic_one.agents.user_proxy import UserProxy from autogen_magentic_one.messages import BroadcastMessage from autogen_magentic_one.utils import LogHandl
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/interface/magentic_one_helper.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
import importlib.metadata ABOUT = "This is Magentic-One." __version__ = importlib.metadata.version("autogen_magentic_one")
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/__init__.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
from dataclasses import dataclass from typing import Any, Dict, List, Union from autogen_core import FunctionCall, Image from autogen_core.models import FunctionExecutionResult, LLMMessage from pydantic import BaseModel # Convenience type UserContent = Union[str, List[Union[str, Image]]] AssistantContent = Union[str, List[FunctionCall]] FunctionExecutionContent = List[FunctionExecutionResult] SystemContent = str # the below are message types used in MagenticOne # used by all agents to send messages class BroadcastMessage(BaseModel): content: LLMMessage request_halt: bool = False # used by orchestrator to obtain a response from an agent @dataclass class RequestReplyMessage: pass # used by orchestrator to reset an agent @dataclass class ResetMessage: pass # used by orchestrator to deactivate an agent @dataclass class DeactivateMessage: pass # orchestrator events @dataclass class OrchestrationEvent: source: str message: str MagenticOneMessages =
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/messages.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
import json import logging import os from dataclasses import asdict from datetime import datetime from typing import Any, Dict, List, Literal from autogen_core import Image from autogen_core.logging import LLMCallEvent from autogen_core.models import ( ChatCompletionClient, ModelCapabilities, # type: ignore ) from autogen_ext.models.openai import AzureOpenAIChatCompletionClient, OpenAIChatCompletionClient from .messages import ( AgentEvent, AssistantContent, FunctionExecutionContent, OrchestrationEvent, SystemContent, UserContent, WebSurferEvent, ) ENVIRON_KEY_CHAT_COMPLETION_PROVIDER = "CHAT_COMPLETION_PROVIDER" ENVIRON_KEY_CHAT_COMPLETION_KWARGS_JSON = "CHAT_COMPLETION_KWARGS_JSON" # The singleton _default_azure_ad_token_provider, which will be created if needed _default_azure_ad_token_provider = None # Create a model client based on information provided in environment variables. def create_completion_client_from_env(env: Dict[str, str] | No
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/utils.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/agents/__init__.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
import asyncio import logging from typing import Any from autogen_core import EVENT_LOGGER_NAME, MessageContext, RoutedAgent, message_handler from autogen_magentic_one.messages import ( AgentEvent, BroadcastMessage, DeactivateMessage, MagenticOneMessages, RequestReplyMessage, ResetMessage, ) class MagenticOneBaseAgent(RoutedAgent): """An agent that optionally ensures messages are handled non-concurrently in the order they arrive.""" def __init__( self, description: str, handle_messages_concurrently: bool = False, ) -> None: super().__init__(description) self._handle_messages_concurrently = handle_messages_concurrently self._enabled = True self.logger = logging.getLogger(EVENT_LOGGER_NAME + f".{self.id.key}.agent") if not self._handle_messages_concurrently: # TODO: make it possible to stop self._message_queue = asyncio.Queue[tuple[MagenticOneMessages, Message
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/agents/base_agent.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
import logging import time from typing import List, Optional from autogen_core import EVENT_LOGGER_NAME, AgentProxy, CancellationToken, MessageContext from autogen_core.models import AssistantMessage, LLMMessage, UserMessage from ..messages import BroadcastMessage, OrchestrationEvent, RequestReplyMessage, ResetMessage from ..utils import message_content_to_str from .base_agent import MagenticOneBaseAgent class BaseOrchestrator(MagenticOneBaseAgent): """Base class for orchestrator that manage a group of agents.""" def __init__( self, agents: List[AgentProxy], description: str = "Base orchestrator", max_rounds: int = 20, max_time: float = float("inf"), handle_messages_concurrently: bool = False, ) -> None: super().__init__(description, handle_messages_concurrently=handle_messages_concurrently) self._agents = agents self._max_rounds = max_rounds self._max_time = max_time self._num_roun
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/agents/base_orchestrator.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
from typing import List, Tuple from autogen_core import CancellationToken, MessageContext, TopicId from autogen_core.models import ( AssistantMessage, LLMMessage, UserMessage, ) from autogen_magentic_one.messages import ( BroadcastMessage, RequestReplyMessage, ResetMessage, UserContent, ) from ..utils import message_content_to_str from .base_agent import MagenticOneBaseAgent class BaseWorker(MagenticOneBaseAgent): """Base agent that handles the MagenticOne worker behavior protocol.""" def __init__( self, description: str, handle_messages_concurrently: bool = False, ) -> None: super().__init__(description, handle_messages_concurrently=handle_messages_concurrently) self._chat_history: List[LLMMessage] = [] async def _handle_broadcast(self, message: BroadcastMessage, ctx: MessageContext) -> None: assert isinstance(message.content, UserMessage) self._chat_history.append(message.conten
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/agents/base_worker.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
import re from typing import Awaitable, Callable, List, Literal, Tuple, Union from autogen_core import CancellationToken, default_subscription from autogen_core.code_executor import CodeBlock, CodeExecutor from autogen_core.models import ( ChatCompletionClient, SystemMessage, UserMessage, ) from ..messages import UserContent from ..utils import message_content_to_str from .base_worker import BaseWorker @default_subscription class Coder(BaseWorker): """An agent that can write code or text to solve tasks without additional tools.""" DEFAULT_DESCRIPTION = "A helpful and general-purpose AI assistant that has strong language skills, Python skills, and Linux command line skills." DEFAULT_SYSTEM_MESSAGES = [ SystemMessage( content="""You are a helpful AI assistant. Solve tasks using your coding and language skills. In the following cases, suggest python code (in a python coding block) or shell script (in a sh coding block) for the user to exec
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/agents/coder.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
import json from typing import Any, Dict, List, Optional from autogen_core import AgentProxy, CancellationToken, MessageContext, TopicId, default_subscription from autogen_core.models import ( AssistantMessage, ChatCompletionClient, LLMMessage, SystemMessage, UserMessage, ) from ..messages import BroadcastMessage, OrchestrationEvent, ResetMessage from .base_orchestrator import BaseOrchestrator from .orchestrator_prompts import ( ORCHESTRATOR_CLOSED_BOOK_PROMPT, ORCHESTRATOR_GET_FINAL_ANSWER, ORCHESTRATOR_LEDGER_PROMPT, ORCHESTRATOR_PLAN_PROMPT, ORCHESTRATOR_SYNTHESIZE_PROMPT, ORCHESTRATOR_SYSTEM_MESSAGE, ORCHESTRATOR_UPDATE_FACTS_PROMPT, ORCHESTRATOR_UPDATE_PLAN_PROMPT, ) @default_subscription class RoundRobinOrchestrator(BaseOrchestrator): """A simple orchestrator that selects agents in a round-robin fashion.""" def __init__( self, agents: List[AgentProxy], description: str = "Round robin orchestr
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/agents/orchestrator.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
ORCHESTRATOR_SYSTEM_MESSAGE = "" ORCHESTRATOR_CLOSED_BOOK_PROMPT = """Below I will present you a request. Before we begin addressing the request, please answer the following pre-survey to the best of your ability. Keep in mind that you are Ken Jennings-level with trivia, and Mensa-level with puzzles, so there should be a deep well to draw from. Here is the request: {task} Here is the pre-survey: 1. Please list any specific facts or figures that are GIVEN in the request itself. It is possible that there are none. 2. Please list any facts that may need to be looked up, and WHERE SPECIFICALLY they might be found. In some cases, authoritative sources are mentioned in the request itself. 3. Please list any facts that may need to be derived (e.g., via logical deduction, simulation, or computation) 4. Please list any facts that are recalled from memory, hunches, well-reasoned guesses, etc. When answering this survey, keep in mind that "facts" will typically be specific
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/agents/orchestrator_prompts.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
import asyncio from typing import Tuple from autogen_core import CancellationToken, default_subscription from ..messages import UserContent from .base_worker import BaseWorker @default_subscription class UserProxy(BaseWorker): """An agent that allows the user to play the role of an agent in the conversation via input.""" DEFAULT_DESCRIPTION = "A human user." def __init__( self, description: str = DEFAULT_DESCRIPTION, ) -> None: super().__init__(description) async def _generate_reply(self, cancellation_token: CancellationToken) -> Tuple[bool, UserContent]: """Respond to a reply request.""" # Make an inference to the model. response = await self.ainput("User input ('exit' to quit): ") response = response.strip() return response == "exit", response async def ainput(self, prompt: str) -> str: return await asyncio.to_thread(input, f"{prompt} ")
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/agents/user_proxy.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
from .file_surfer import FileSurfer __all__ = ["FileSurfer"]
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/agents/file_surfer/__init__.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
from autogen_core.tools import ParametersSchema, ToolSchema TOOL_OPEN_LOCAL_FILE = ToolSchema( name="open_local_file", description="Open a local file at a path in the text-based browser and return current viewport content.", parameters=ParametersSchema( type="object", properties={ "path": { "type": "string", "description": "The relative or absolute path of a local file to visit.", }, }, required=["path"], ), ) TOOL_PAGE_UP = ToolSchema( name="page_up", description="Scroll the viewport UP one page-length in the current file and return the new viewport content.", ) TOOL_PAGE_DOWN = ToolSchema( name="page_down", description="Scroll the viewport DOWN one page-length in the current file and return the new viewport content.", ) TOOL_FIND_ON_PAGE_CTRL_F = ToolSchema( name="find_on_page_ctrl_f", description="Scroll the viewport to the first occurrence of the se
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/agents/file_surfer/_tools.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
import json import time from typing import List, Optional, Tuple from autogen_core import CancellationToken, FunctionCall, default_subscription from autogen_core.models import ( ChatCompletionClient, SystemMessage, UserMessage, ) from ...markdown_browser import RequestsMarkdownBrowser from ..base_worker import BaseWorker # from typing_extensions import Annotated from ._tools import TOOL_FIND_NEXT, TOOL_FIND_ON_PAGE_CTRL_F, TOOL_OPEN_LOCAL_FILE, TOOL_PAGE_DOWN, TOOL_PAGE_UP @default_subscription class FileSurfer(BaseWorker): """An agent that uses tools to read and navigate local files.""" DEFAULT_DESCRIPTION = "An agent that can handle local files." DEFAULT_SYSTEM_MESSAGES = [ SystemMessage( content=""" You are a helpful AI Assistant. When given a user query, use available functions to help the user with their request.""" ), ] def __init__( self, model_client: ChatCompletionClient,
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/agents/file_surfer/file_surfer.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
from .multimodal_web_surfer import MultimodalWebSurfer __all__ = ("MultimodalWebSurfer",)
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/agents/multimodal_web_surfer/__init__.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
import base64 import hashlib import io import json import logging import os import pathlib import re import time import traceback from typing import Any, BinaryIO, Dict, List, Optional, Tuple, Union, cast # Any, Callable, Dict, List, Literal, Tuple from urllib.parse import quote_plus # parse_qs, quote, unquote, urlparse, urlunparse import aiofiles from autogen_core import EVENT_LOGGER_NAME, CancellationToken, FunctionCall, default_subscription from autogen_core import Image as AGImage from autogen_core.models import ( AssistantMessage, ChatCompletionClient, LLMMessage, SystemMessage, UserMessage, ) from PIL import Image from playwright._impl._errors import Error as PlaywrightError from playwright._impl._errors import TimeoutError # from playwright._impl._async_base.AsyncEventInfo from playwright.async_api import BrowserContext, Download, Page, Playwright, async_playwright # TODO: Fix mdconvert from ...markdown_browser import MarkdownConverter # type: ignore fr
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/agents/multimodal_web_surfer/multimodal_web_surfer.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
import io import random from typing import BinaryIO, Dict, List, Tuple, cast from PIL import Image, ImageDraw, ImageFont from .types import DOMRectangle, InteractiveRegion TOP_NO_LABEL_ZONE = 20 # Don't print any labels close the top of the page def add_set_of_mark( screenshot: bytes | Image.Image | io.BufferedIOBase, ROIs: Dict[str, InteractiveRegion] ) -> Tuple[Image.Image, List[str], List[str], List[str]]: if isinstance(screenshot, Image.Image): return _add_set_of_mark(screenshot, ROIs) if isinstance(screenshot, bytes): screenshot = io.BytesIO(screenshot) # TODO: Not sure why this cast was needed, but by this point screenshot is a binary file-like object image = Image.open(cast(BinaryIO, screenshot)) comp, visible_rects, rects_above, rects_below = _add_set_of_mark(image, ROIs) image.close() return comp, visible_rects, rects_above, rects_below def _add_set_of_mark( screenshot: Image.Image, ROIs: Dict[str, InteractiveRegion
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/agents/multimodal_web_surfer/set_of_mark.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
from typing import Any, Dict # TODO Why does pylance fail if I import from autogen_core.tools instead? from autogen_core.tools._base import ParametersSchema, ToolSchema def _load_tool(tooldef: Dict[str, Any]) -> ToolSchema: return ToolSchema( name=tooldef["function"]["name"], description=tooldef["function"]["description"], parameters=ParametersSchema( type="object", properties=tooldef["function"]["parameters"]["properties"], required=tooldef["function"]["parameters"]["required"], ), ) TOOL_VISIT_URL: ToolSchema = _load_tool( { "type": "function", "function": { "name": "visit_url", "description": "Navigate directly to a provided URL using the browser's address bar. Prefer this tool over other navigation techniques in cases where the user provides a fully-qualified URL (e.g., choose it over clicking links, or inputing queries into search boxes).", "para
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/agents/multimodal_web_surfer/tool_definitions.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
from typing import Any, Dict, List, TypedDict, Union class DOMRectangle(TypedDict): x: Union[int, float] y: Union[int, float] width: Union[int, float] height: Union[int, float] top: Union[int, float] right: Union[int, float] bottom: Union[int, float] left: Union[int, float] class VisualViewport(TypedDict): height: Union[int, float] width: Union[int, float] offsetLeft: Union[int, float] offsetTop: Union[int, float] pageLeft: Union[int, float] pageTop: Union[int, float] scale: Union[int, float] clientWidth: Union[int, float] clientHeight: Union[int, float] scrollWidth: Union[int, float] scrollHeight: Union[int, float] class InteractiveRegion(TypedDict): tag_name: str role: str aria_name: str v_scrollable: bool rects: List[DOMRectangle] # Helper functions for dealing with JSON. Not sure there's a better way? def _get_str(d: Any, k: str) -> str: val = d[k] assert isinstance(val
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/agents/multimodal_web_surfer/types.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
from .abstract_markdown_browser import AbstractMarkdownBrowser from .markdown_search import AbstractMarkdownSearch, BingMarkdownSearch # TODO: Fix mdconvert from .mdconvert import ( # type: ignore DocumentConverterResult, FileConversionException, MarkdownConverter, UnsupportedFormatException, ) from .requests_markdown_browser import RequestsMarkdownBrowser __all__ = ( "AbstractMarkdownBrowser", "RequestsMarkdownBrowser", "AbstractMarkdownSearch", "BingMarkdownSearch", "MarkdownConverter", "UnsupportedFormatException", "FileConversionException", "DocumentConverterResult", )
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/markdown_browser/__init__.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
from abc import ABC, abstractmethod from typing import Union class AbstractMarkdownBrowser(ABC): """ An abstract class for a Markdown web browser. All MarkdownBrowers work by: (1) fetching a web page by URL (via requests, Selenium, Playwright, etc.) (2) converting the page's HTML or DOM to Markdown (3) operating on the Markdown Such browsers are simple, and suitable for read-only agentic use. They cannot be used to interact with complex web applications. """ @abstractmethod def __init__(self) -> None: pass @property @abstractmethod def address(self) -> str: pass @abstractmethod def set_address(self, uri_or_path: str) -> None: pass @property @abstractmethod def viewport(self) -> str: pass @property @abstractmethod def page_content(self) -> str: pass @abstractmethod def page_down(self) -> None: pass @abstractmethod
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/markdown_browser/abstract_markdown_browser.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
import logging import os import re from abc import ABC, abstractmethod from typing import Any, Dict, List, Optional, cast from urllib.parse import quote, quote_plus, unquote, urlparse, urlunparse import requests # TODO: Fix these types from .mdconvert import MarkdownConverter # type: ignore logger = logging.getLogger(__name__) class AbstractMarkdownSearch(ABC): """ An abstract class for providing search capabilities to a Markdown browser. """ @abstractmethod def search(self, query: str) -> str: pass class BingMarkdownSearch(AbstractMarkdownSearch): """ Provides Bing web search capabilities to Markdown browsers. """ def __init__(self, bing_api_key: Optional[str] = None, interleave_results: bool = True): """ Perform a Bing web search, and return the results formatted in Markdown. Args: bing_api_key: key for the Bing search API. If omitted, an attempt is made to read the key from the BING_API_KEY en
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/markdown_browser/markdown_search.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
# type: ignore import base64 import binascii import copy import html import json import mimetypes import os import re import shutil import subprocess import sys import tempfile from typing import Any, Dict, List, Optional, Union from urllib.parse import parse_qs, quote, unquote, urlparse, urlunparse import mammoth import markdownify import pandas as pd import pdfminer import pdfminer.high_level import pptx # File-format detection import puremagic import requests from bs4 import BeautifulSoup # Optional Transcription support try: import pydub import speech_recognition as sr IS_AUDIO_TRANSCRIPTION_CAPABLE = True except ModuleNotFoundError: pass # Optional YouTube transcription support try: from youtube_transcript_api import YouTubeTranscriptApi IS_YOUTUBE_TRANSCRIPT_CAPABLE = True except ModuleNotFoundError: pass class _CustomMarkdownify(markdownify.MarkdownConverter): """ A custom version of markdownify's MarkdownConverter. Changes include:
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/markdown_browser/mdconvert.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
# ruff: noqa: E722 import datetime import html import io import mimetypes import os import pathlib import re import time import traceback import uuid from typing import Any, Dict, List, Optional, Tuple, Union from urllib.parse import unquote, urljoin, urlparse import pathvalidate import requests from .abstract_markdown_browser import AbstractMarkdownBrowser from .markdown_search import AbstractMarkdownSearch, BingMarkdownSearch # TODO: Fix unfollowed import from .mdconvert import FileConversionException, MarkdownConverter, UnsupportedFormatException # type: ignore class RequestsMarkdownBrowser(AbstractMarkdownBrowser): """ (In preview) An extremely simple Python requests-powered Markdown web browser. This browser cannot run JavaScript, compute CSS, etc. It simply fetches the HTML document, and converts it to Markdown. See AbstractMarkdownBrowser for more details. """ # TODO: Fix unfollowed import def __init__( # type: ignore self, sta
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/src/autogen_magentic_one/markdown_browser/requests_markdown_browser.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
#!/usr/bin/env python3 -m pytest import os import pytest from autogen_magentic_one.markdown_browser import BingMarkdownSearch skip_all = False bing_api_key = None if "BING_API_KEY" in os.environ: bing_api_key = os.environ["BING_API_KEY"] del os.environ["BING_API_KEY"] skip_api = bing_api_key is None BING_QUERY = "Microsoft wikipedia" BING_STRING = f"A Bing search for '{BING_QUERY}' found" BING_EXPECTED_RESULT = "https://en.wikipedia.org/wiki/Microsoft" @pytest.mark.skipif( skip_api, reason="skipping tests that require a Bing API key", ) def test_bing_markdown_search_api() -> None: search_engine = BingMarkdownSearch(bing_api_key=bing_api_key) results = search_engine.search(BING_QUERY) assert BING_STRING in results assert BING_EXPECTED_RESULT in results if __name__ == "__main__": """Runs this file's tests from the command line.""" test_bing_markdown_search_api()
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/tests/browser_utils/test_bing_markdown_search.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
#!/usr/bin/env python3 -m pytest import io import os import shutil import pytest import requests from autogen_magentic_one.markdown_browser import MarkdownConverter skip_all = False skip_exiftool = shutil.which("exiftool") is None TEST_FILES_DIR = os.path.join(os.path.dirname(__file__), "test_files") JPG_TEST_EXIFTOOL = { "Author": "AutoGen Authors", "Title": "AutoGen: Enabling Next-Gen LLM Applications via Multi-Agent Conversation", "Description": "AutoGen enables diverse LLM-based applications", "ImageSize": "1615x1967", "DateTimeOriginal": "2024:03:14 22:10:00", } PDF_TEST_URL = "https://arxiv.org/pdf/2308.08155v2.pdf" PDF_TEST_STRINGS = ["While there is contemporaneous exploration of multi-agent approaches"] YOUTUBE_TEST_URL = "https://www.youtube.com/watch?v=V2qZ_lgxTzg" YOUTUBE_TEST_STRINGS = [ "## AutoGen FULL Tutorial with Python (Step-By-Step)", "This is an intermediate tutorial for installing and using AutoGen locally", "PT15M4S", "t
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/tests/browser_utils/test_mdconvert.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
#!/usr/bin/env python3 -m pytest import hashlib import math import os import pathlib import re import pytest import requests from autogen_magentic_one.markdown_browser import BingMarkdownSearch, RequestsMarkdownBrowser BLOG_POST_URL = "https://microsoft.github.io/autogen/0.2/blog/2023/04/21/LLM-tuning-math" BLOG_POST_TITLE = "Does Model and Inference Parameter Matter in LLM Applications? - A Case Study for MATH | AutoGen" BLOG_POST_STRING = "Large language models (LLMs) are powerful tools that can generate natural language texts for various applications, such as chatbots, summarization, translation, and more. GPT-4 is currently the state of the art LLM in the world. Is model selection irrelevant? What about inference parameters?" BLOG_POST_FIND_ON_PAGE_QUERY = "an example where high * complex" BLOG_POST_FIND_ON_PAGE_MATCH = "an example where high cost can easily prevent a generic complex" WIKIPEDIA_URL = "https://en.wikipedia.org/wiki/Microsoft" WIKIPEDIA_TITLE = "Microsoft" WIKIPE
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/tests/browser_utils/test_requests_markdown_browser.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
skip_openai: bool = False skip_redis: bool = False skip_docker: bool = False reason: str = "requested to skip" MOCK_OPEN_AI_API_KEY: str = "sk-mockopenaiAPIkeyinexpectedformatfortestingonly" MOCK_CHAT_COMPLETION_KWARGS: str = """ { "api_key": "sk-mockopenaiAPIkeyinexpectedformatfortestingonly", "model": "gpt-4o-2024-05-13" } """
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/tests/headless_web_surfer/conftest.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
#!/usr/bin/env python3 -m pytest import asyncio import os import re from json import dumps from math import ceil from typing import Mapping import pytest from autogen_core import AgentId, AgentProxy, FunctionCall, SingleThreadedAgentRuntime from autogen_core.models import ( UserMessage, ) from autogen_core.tools._base import ToolSchema from autogen_magentic_one.agents.multimodal_web_surfer import MultimodalWebSurfer from autogen_magentic_one.agents.multimodal_web_surfer.tool_definitions import ( TOOL_PAGE_DOWN, TOOL_PAGE_UP, TOOL_READ_PAGE_AND_ANSWER, TOOL_SUMMARIZE_PAGE, TOOL_VISIT_URL, TOOL_WEB_SEARCH, ) from autogen_magentic_one.agents.orchestrator import RoundRobinOrchestrator from autogen_magentic_one.agents.user_proxy import UserProxy from autogen_magentic_one.messages import BroadcastMessage from autogen_magentic_one.utils import ( ENVIRON_KEY_CHAT_COMPLETION_KWARGS_JSON, ENVIRON_KEY_CHAT_COMPLETION_PROVIDER, create_completion_client_fro
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/tests/headless_web_surfer/test_web_surfer.py", "file_type": ".py", "source_type": "code" }
Analyze this document content
# 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
Document summary and key points
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/README.md", "file_type": ".md", "source_type": "document" }
Analyze this code content
from setuptools import setup setup()
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/setup.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
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__", ]
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/__init__.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
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
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/cli.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
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,
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/teammanager.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
VERSION = "0.4.0.dev41" __version__ = VERSION APP_NAME = "autogenstudio"
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/version.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
from .component_factory import Component, ComponentFactory from .config_manager import ConfigurationManager from .db_manager import DatabaseManager
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/database/__init__.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
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
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/database/component_factory.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
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
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/database/config_manager.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
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)
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/database/db_manager.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
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
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/database/schema_manager.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
from .db import Agent, LinkTypes, Message, Model, Run, RunStatus, Session, Team, Tool from .types import ( AgentConfig, ComponentConfigInput, MessageConfig, ModelConfig, Response, TeamConfig, TeamResult, ToolConfig, )
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/datamodel/__init__.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
# 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"
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/datamodel/db.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
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"
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/datamodel/types.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/utils/__init__.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
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
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/utils/utils.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/web/__init__.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
# 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
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/web/app.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
# 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 = "[email protected]" UPGRADE_DATABASE: bool = False class Config: env_prefix = "AUTOGENSTUDIO_" settings = Settings()
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/web/config.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
# 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
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/web/deps.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
# 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
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/web/initialization.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
# 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
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/web/serve.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
from .connection import WebSocketManager
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/web/managers/__init__.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
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] = {}
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/web/managers/connection.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/web/routes/__init__.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
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
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/web/routes/agents.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
# 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
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/web/routes/gallery.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
# 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
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/web/routes/models.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
# /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.
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/web/routes/runs.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
# 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
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/web/routes/sessions.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
# 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
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/web/routes/teams.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
# 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
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/web/routes/tools.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
# 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]:
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/autogenstudio/web/routes/ws.py", "file_type": ".py", "source_type": "code" }
Analyze this document content
## 🚀 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
Document summary and key points
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/frontend/README.md", "file_type": ".md", "source_type": "document" }
Analyze this code content
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/tests/__init__.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
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
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/tests/test_component_factory.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
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
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-studio/tests/test_db_manager.py", "file_type": ".py", "source_type": "code" }
Analyze this document content
# test-utils
Document summary and key points
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-test-utils/README.md", "file_type": ".md", "source_type": "document" }
Analyze this code content
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
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-test-utils/src/autogen_test_utils/__init__.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
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
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/autogen-test-utils/src/autogen_test_utils/telemetry_test_utils.py", "file_type": ".py", "source_type": "code" }
Analyze this document content
# 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.
Document summary and key points
{ "file_path": "multi_repo_data/autogen/python/packages/component-schema-gen/README.md", "file_type": ".md", "source_type": "document" }
Analyze this code content
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/component-schema-gen/src/component_schema_gen/__init__.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
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
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/packages/component-schema-gen/src/component_schema_gen/__main__.py", "file_type": ".py", "source_type": "code" }
Analyze this document content
# 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
Document summary and key points
{ "file_path": "multi_repo_data/autogen/python/samples/agentchat_chainlit/README.md", "file_type": ".md", "source_type": "document" }
Analyze this code content
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
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/samples/agentchat_chainlit/app.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
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)
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/templates/new-package/hooks/post_gen_project.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
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)
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/templates/new-package/hooks/pre_gen_project.py", "file_type": ".py", "source_type": "code" }
Analyze this document content
# {{cookiecutter.package_name}}
Document summary and key points
{ "file_path": "multi_repo_data/autogen/python/templates/new-package/{{cookiecutter.package_name}}/README.md", "file_type": ".md", "source_type": "document" }
Analyze this code content
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/templates/new-package/{{cookiecutter.package_name}}/src/{{cookiecutter.__project_slug}}/__init__.py", "file_type": ".py", "source_type": "code" }
Analyze this code content
async def test_example() -> None: assert True
Code analysis and explanation
{ "file_path": "multi_repo_data/autogen/python/templates/new-package/{{cookiecutter.package_name}}/tests/test_example.py", "file_type": ".py", "source_type": "code" }