Instruction: Analyze this code content

Input:
import asyncio
import json
from typing import Any, AsyncGenerator, List, Mapping, Optional, Sequence, Union

import pytest
from autogen_core import AgentId, CancellationToken, FunctionCall, SingleThreadedAgentRuntime
from autogen_core.models import (
    AssistantMessage,
    ChatCompletionClient,
    CreateResult,
    FunctionExecutionResult,
    FunctionExecutionResultMessage,
    LLMMessage,
    ModelCapabilities,  # type: ignore
    RequestUsage,
    UserMessage,
)
from autogen_core.models._model_client import ModelFamily, ModelInfo
from autogen_core.tool_agent import (
    InvalidToolArgumentsException,
    ToolAgent,
    ToolExecutionException,
    ToolNotFoundException,
    tool_agent_caller_loop,
)
from autogen_core.tools import FunctionTool, Tool, ToolSchema

def _pass_function(input: str) -> str:
    return "pass"

def _raise_function(input: str) -> str:
    raise Exception("raise")

async def _async_sleep_function(input: str) -> str:
    await asyncio.sleep(10)
    return

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import inspect
from typing import Annotated, List

import pytest
from autogen_core import CancellationToken
from autogen_core._function_utils import get_typed_signature
from autogen_core.tools import BaseTool, FunctionTool
from autogen_core.tools._base import ToolSchema
from pydantic import BaseModel, Field, model_serializer
from pydantic_core import PydanticUndefined

class MyArgs(BaseModel):
    query: str = Field(description="The description.")

class MyNestedArgs(BaseModel):
    arg: MyArgs = Field(description="The nested description.")

class MyResult(BaseModel):
    result: str = Field(description="The other description.")

class MyTool(BaseTool[MyArgs, MyResult]):
    def __init__(self) -> None:
        super().__init__(
            args_type=MyArgs,
            return_type=MyResult,
            name="TestTool",
            description="Description of test tool.",
        )
        self.called_count = 0

    async def run(self, args: MyArgs, cancellation_token: CancellationT

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from dataclasses import dataclass
from types import NoneType
from typing import Any, List, Optional, Union

from autogen_core import MessageContext
from autogen_core._routed_agent import RoutedAgent, message_handler
from autogen_core._serialization import has_nested_base_model
from autogen_core._type_helpers import AnyType, get_types
from pydantic import BaseModel

def test_get_types() -> None:
    assert get_types(Union[int, str]) == (int, str)
    assert get_types(int | str) == (int, str)
    assert get_types(int) == (int,)
    assert get_types(str) == (str,)
    assert get_types("test") is None
    assert get_types(Optional[int]) == (int, NoneType)
    assert get_types(NoneType) == (NoneType,)
    assert get_types(None) == (NoneType,)

def test_handler() -> None:
    class HandlerClass(RoutedAgent):
        @message_handler()
        async def handler(self, message: int, ctx: MessageContext) -> Any:
            return None

        @message_handler()
        async def handler2(sel

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: serialization_test.proto
# Protobuf Python Version: 4.25.1
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder
# @@protoc_insertion_point(imports)

_sym_db = _symbol_database.Default()

DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x18serialization_test.proto\x12\x06\x61gents\"\x1f\n\x0cProtoMessage\x12\x0f\n\x07message\x18\x01 \x01(\t\"L\n\x13NestingProtoMessage\x12\x0f\n\x07message\x18\x01 \x01(\t\x12$\n\x06nested\x18\x02 \x01(\x0b\x32\x14.agents.ProtoMessageb\x06proto3')

_globals = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'serialization_test_pb2', _globals)
if _descrip

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import asyncio
import typing as t
from functools import partial
from typing import Protocol

import asyncio_atexit
import pytest

class AtExitImpl(Protocol):
    def register(self, func: t.Callable[..., t.Any], /, *args: t.Any, **kwargs: t.Any) -> t.Callable[..., t.Any]: ...
    def unregister(self, func: t.Callable[..., t.Any], /) -> None: ...

class AtExitSimulator(AtExitImpl):
    def __init__(self) -> None:
        self._funcs: t.List[t.Callable[..., t.Any]] = []

    def complete(self) -> None:
        for func in self._funcs:
            func()

        self._funcs.clear()

    def register(self, func: t.Callable[..., t.Any], /, *args: t.Any, **kwargs: t.Any) -> t.Callable[..., t.Any]:
        self._funcs.append(func)
        return func

    def unregister(self, func: t.Callable[..., t.Any], /) -> None:
        self._funcs.remove(func)

class AsyncioAtExitWrapper(AtExitImpl):
    """This only exists to make mypy happy"""

    def register(self, func: t.Callable[..., t.Any], /

Output: Code analysis and explanation


Instruction: Analyze this document content

Input: # autogen-ext

Output: Document summary and key points


Instruction: Analyze this code content

Input:
import importlib.metadata

__version__ = importlib.metadata.version("autogen_ext")

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from ._file_surfer import FileSurfer

__all__ = ["FileSurfer"]

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import json
import traceback
from typing import List, Sequence, Tuple

from autogen_agentchat.agents import BaseChatAgent
from autogen_agentchat.base import Response
from autogen_agentchat.messages import (
    ChatMessage,
    MultiModalMessage,
    TextMessage,
)
from autogen_core import CancellationToken, FunctionCall
from autogen_core.models import (
    AssistantMessage,
    ChatCompletionClient,
    LLMMessage,
    SystemMessage,
    UserMessage,
)

from ._markdown_file_browser import MarkdownFileBrowser

# from typing_extensions import Annotated
from ._tool_definitions import (
    TOOL_FIND_NEXT,
    TOOL_FIND_ON_PAGE_CTRL_F,
    TOOL_OPEN_PATH,
    TOOL_PAGE_DOWN,
    TOOL_PAGE_UP,
)

class FileSurfer(BaseChatAgent):
    """An agent, used by MagenticOne, that acts as a local file previewer. FileSurfer can open and read a variety of common file types, and can navigate the local file hierarchy.

    Installation:

    .. code-block:: bash

        pip install "autogen-ext[file-

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# ruff: noqa: E722
import datetime
import io
import os
import re
import time
from typing import List, Optional, Tuple, Union

# TODO: Fix unfollowed import
from markitdown import FileConversionException, MarkItDown, UnsupportedFormatException  # type: ignore

class MarkdownFileBrowser:
    """
    (In preview) An extremely simple Markdown-powered file browser.
    """

    # TODO: Fix unfollowed import
    def __init__(  # type: ignore
        self, viewport_size: Union[int, None] = 1024 * 8
    ):
        """
        Instantiate a new MarkdownFileBrowser.

        Arguments:
            viewport_size: Approximately how many *characters* fit in the viewport. Viewport dimensions are adjusted dynamically to avoid cutting off words (default: 8192).
        """
        self.viewport_size = viewport_size  # Applies only to the standard uri types
        self.history: List[Tuple[str, float]] = list()
        self.page_title: Optional[str] = None
        self.viewport_current_page = 0

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from autogen_core.tools import ParametersSchema, ToolSchema

TOOL_OPEN_PATH = ToolSchema(
    name="open_path",
    description="Open a local file or directory at a path in the text-based file 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

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
try:
    from ._magentic_one_coder_agent import MagenticOneCoderAgent
except ImportError as e:
    raise ImportError(
        "Dependencies for MagenticOneCoderAgent not found. "
        'Please install autogen-ext with the "magentic-one" extra: '
        'pip install "autogen-ext[magentic-one]"'
    ) from e

__all__ = ["MagenticOneCoderAgent"]

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from autogen_agentchat.agents import AssistantAgent
from autogen_core.models import (
    ChatCompletionClient,
)

MAGENTIC_ONE_CODER_DESCRIPTION = "A helpful and general-purpose AI assistant that has strong language skills, Python skills, and Linux command line skills."

MAGENTIC_ONE_CODER_SYSTEM_MESSAGE = """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 execute.
    1. When you need to collect info, use the code to output the info you need, for example, browse or search the web, download/read a file, print the content of a webpage or a file, get the current date/time, check the operating system. After sufficient info is printed and the task is ready to be solved based on your language skill, you can solve the task by yourself.
    2. When you need to perform some task with code, use the code to perform the task and output t

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
try:
    from ._openai_assistant_agent import OpenAIAssistantAgent
except ImportError as e:
    raise ImportError(
        "Dependencies for OpenAIAssistantAgent not found. "
        'Please install autogen-ext with the "openai" extra: '
        'pip install "autogen-ext[openai]"'
    ) from e

__all__ = ["OpenAIAssistantAgent"]

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import asyncio
import json
import logging
import os
from typing import (
    TYPE_CHECKING,
    Any,
    AsyncGenerator,
    Awaitable,
    Callable,
    Dict,
    Iterable,
    List,
    Literal,
    Optional,
    Sequence,
    Set,
    Union,
    cast,
)

from autogen_agentchat import EVENT_LOGGER_NAME
from autogen_agentchat.agents import BaseChatAgent
from autogen_agentchat.base import Response
from autogen_agentchat.messages import (
    AgentEvent,
    ChatMessage,
    HandoffMessage,
    MultiModalMessage,
    StopMessage,
    TextMessage,
    ToolCallExecutionEvent,
    ToolCallRequestEvent,
)
from autogen_core import CancellationToken, FunctionCall
from autogen_core.models._types import FunctionExecutionResult
from autogen_core.tools import FunctionTool, Tool

_has_openai_dependencies: bool = True
try:
    import aiofiles

    from openai import NOT_GIVEN
    from openai.resources.beta.threads import AsyncMessages, AsyncRuns, AsyncThreads
    from openai.types.beta.code_interpr

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from ._video_surfer import VideoSurfer

__all__ = ["VideoSurfer"]

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from typing import Any, Awaitable, Callable, List, Optional

from autogen_agentchat.agents import AssistantAgent
from autogen_core.models import ChatCompletionClient
from autogen_core.tools import Tool

from .tools import (
    extract_audio,
    get_screenshot_at,
    get_video_length,
    save_screenshot,
    transcribe_audio_with_timestamps,
    transcribe_video_screenshot,
)

class VideoSurfer(AssistantAgent):
    """
    VideoSurfer is a specialized agent designed to answer questions about a local video file.

    Installation:

    .. code-block:: bash

        pip install "autogen-ext[video-surfer]==0.4.0.dev13"

    This agent utilizes various tools to extract information from the video, such as its length, screenshots at specific timestamps, and audio transcriptions. It processes these elements to provide detailed answers to user queries.

    Available tools:

    - :func:`~autogen_ext.agents.video_surfer.tools.extract_audio`
    - :func:`~autogen_ext.agents.video_surfer.too

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import base64
from typing import Any, Dict, List, Tuple

import cv2
import ffmpeg
import numpy as np
import whisper
from autogen_core import Image as AGImage
from autogen_core.models import (
    ChatCompletionClient,
    UserMessage,
)

def extract_audio(video_path: str, audio_output_path: str) -> str:
    """
    Extracts audio from a video file and saves it as an MP3 file.

    :param video_path: Path to the video file.
    :param audio_output_path: Path to save the extracted audio file.
    :return: Confirmation message with the path to the saved audio file.
    """
    (ffmpeg.input(video_path).output(audio_output_path, format="mp3").run(quiet=True, overwrite_output=True))  # type: ignore
    return f"Audio extracted and saved to {audio_output_path}."

def transcribe_audio_with_timestamps(audio_path: str) -> str:
    """
    Transcribes the audio file with timestamps using the Whisper model.

    :param audio_path: Path to the audio file.
    :return: Transcription with timestam

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from ._multimodal_web_surfer import MultimodalWebSurfer
from .playwright_controller import PlaywrightController

__all__ = ["MultimodalWebSurfer", "PlaywrightController"]

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from dataclasses import dataclass
from typing import Any, Dict

@dataclass
class WebSurferEvent:
    source: str
    message: str
    url: str
    action: str | None = None
    arguments: Dict[str, Any] | None = None

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import base64
import hashlib
import io
import json
import logging
import os
import re
import time
import traceback
from typing import (
    Any,
    AsyncGenerator,
    BinaryIO,
    Dict,
    List,
    Optional,
    Sequence,
    cast,
)
from urllib.parse import quote_plus

import aiofiles
import PIL.Image
from autogen_agentchat.agents import BaseChatAgent
from autogen_agentchat.base import Response
from autogen_agentchat.messages import AgentEvent, ChatMessage, MultiModalMessage, TextMessage
from autogen_core import EVENT_LOGGER_NAME, CancellationToken, FunctionCall
from autogen_core import Image as AGImage
from autogen_core.models import (
    AssistantMessage,
    ChatCompletionClient,
    LLMMessage,
    RequestUsage,
    SystemMessage,
    UserMessage,
)
from PIL import Image
from playwright.async_api import BrowserContext, Download, Page, Playwright, async_playwright

from ._events import WebSurferEvent
from ._prompts import WEB_SURFER_OCR_PROMPT, WEB_SURFER_QA_PROMPT, WEB_SURFE

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
WEB_SURFER_TOOL_PROMPT = """
Consider the following screenshot of a web browser, which is open to the page '{url}'. In this screenshot, interactive elements are outlined in bounding boxes of different colors. Each bounding box has a numeric ID label in the same color. Additional information about each visible label is listed below:

{visible_targets}{other_targets_str}{focused_hint}

You are to respond to the most recent request by selecting an appropriate tool from the following set, or by answering the question directly if possible without tools:

{tool_names}

When deciding between tools, consider if the request can be best addressed by:
    - the contents of the current viewport (in which case actions like clicking links, clicking buttons, inputting text might be most appropriate, or hovering over element)
    - contents found elsewhere on the full webpage (in which case actions like scrolling, summarization, or full-page Q&A might be most appropriate)
    - on some other website e

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
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, InteractiveRegio

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from typing import Any, Dict

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"],
        ),
    )

REASONING_TOOL_PROMPT = (
    "A short description of the action to be performed and reason for doing so, do not mention the user."
)

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

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from typing import Any, Dict, List, TypedDict, Union

from autogen_core import FunctionCall, Image
from autogen_core.models import FunctionExecutionResult

UserContent = Union[str, List[Union[str, Image]]]
AssistantContent = Union[str, List[FunctionCall]]
FunctionExecutionContent = List[FunctionExecutionResult]
SystemContent = str

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 Interact

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from typing import List

from autogen_core import Image

from ._types import AssistantContent, FunctionExecutionContent, SystemContent, UserContent

# Convert UserContent to a string
def message_content_to_str(
    message_content: UserContent | AssistantContent | SystemContent | FunctionExecutionContent,
) -> str:
    if isinstance(message_content, str):
        return message_content
    elif isinstance(message_content, List):
        converted: List[str] = list()
        for item in message_content:
            if isinstance(item, str):
                converted.append(item.rstrip())
            elif isinstance(item, Image):
                converted.append("<Image>")
            else:
                converted.append(str(item).rstrip())
        return "\n".join(converted)
    else:
        raise AssertionError("Unexpected response type.")

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import asyncio
import base64
import io
import os
import random
from typing import Any, Callable, Dict, Optional, Tuple, Union, cast

# TODO: Fix unfollowed import
try:
    from markitdown import MarkItDown  # type: ignore
except ImportError:
    MarkItDown = None
from playwright._impl._errors import Error as PlaywrightError
from playwright._impl._errors import TimeoutError
from playwright.async_api import Download, Page

from ._types import (
    InteractiveRegion,
    VisualViewport,
    interactiveregion_from_dict,
    visualviewport_from_dict,
)

class PlaywrightController:
    """
    A helper class to allow Playwright to interact with web pages to perform actions such as clicking, filling, and scrolling.

    Args:
        downloads_folder (str | None): The folder to save downloads to. If None, downloads are not saved.
        animate_actions (bool): Whether to animate the actions (create fake cursor to click).
        viewport_width (int): The width of the viewport.
        view

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import inspect
import re
from dataclasses import dataclass
from pathlib import Path
from textwrap import dedent, indent
from typing import Any, Callable, Optional, Sequence, Set, TypeVar, Union

from autogen_core.code_executor import Alias, CodeResult, FunctionWithRequirements, FunctionWithRequirementsStr, Import
from typing_extensions import ParamSpec

@dataclass
class CommandLineCodeResult(CodeResult):
    """A code result class for command line code executor."""

    code_file: Optional[str]

T = TypeVar("T")
P = ParamSpec("P")

def _to_code(func: Union[FunctionWithRequirements[T, P], Callable[P, T], FunctionWithRequirementsStr]) -> str:
    if isinstance(func, FunctionWithRequirementsStr):
        return func.func

    code = inspect.getsource(func)
    # Strip the decorator
    if code.startswith("@"):
        code = code[code.index("\n") + 1 :]
    return code

def _import_to_str(im: Import) -> str:
    if isinstance(im, str):
        return f"import {im}"
    elif isinstance

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from ._azure_container_code_executor import ACADynamicSessionsCodeExecutor, TokenProvider

__all__ = ["TokenProvider", "ACADynamicSessionsCodeExecutor"]

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# Credit to original authors

from __future__ import annotations

import asyncio
import os
from pathlib import Path
from string import Template
from typing import TYPE_CHECKING, Any, Callable, ClassVar, List, Optional, Protocol, Sequence, Union
from uuid import uuid4

import aiohttp

# async functions shouldn't use open()
from anyio import open_file
from autogen_core import CancellationToken
from autogen_core.code_executor import (
    CodeBlock,
    CodeExecutor,
    CodeResult,
    FunctionWithRequirements,
    FunctionWithRequirementsStr,
)
from typing_extensions import ParamSpec

from .._common import build_python_functions_file, get_required_packages, to_stub

if TYPE_CHECKING:
    from azure.core.credentials import AccessToken

PYTHON_VARIANTS = ["python", "Python", "py"]

__all__ = ("ACADynamicSessionsCodeExecutor", "TokenProvider")

A = ParamSpec("A")

class TokenProvider(Protocol):
    def get_token(
        self, *scopes: str, claims: Optional[str] = None, tenant_id: Optiona

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from ._docker_code_executor import DockerCommandLineCodeExecutor

__all__ = ["DockerCommandLineCodeExecutor"]

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# File based from: https://github.com/microsoft/autogen/blob/main/autogen/coding/docker_commandline_code_executor.py
# Credit to original authors

from __future__ import annotations

import asyncio
import logging
import shlex
import sys
import uuid
from collections.abc import Sequence
from hashlib import sha256
from pathlib import Path
from types import TracebackType
from typing import Any, Callable, ClassVar, List, Optional, ParamSpec, Type, Union

from autogen_core import CancellationToken
from autogen_core.code_executor import (
    CodeBlock,
    CodeExecutor,
    FunctionWithRequirements,
    FunctionWithRequirementsStr,
)

from .._common import (
    CommandLineCodeResult,
    build_python_functions_file,
    get_file_name_from_content,
    lang_to_cmd,
    silence_pip,
)

if sys.version_info >= (3, 11):
    from typing import Self
else:
    from typing_extensions import Self

async def _wait_for_ready(container: Any, timeout: int = 60, stop_time: float = 0.1) -> None:
    elaps

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# File based from: https://github.com/microsoft/autogen/blob/main/autogen/coding/local_commandline_code_executor.py
# Credit to original authors

import asyncio
import logging
import os
import sys
import warnings
from hashlib import sha256
from pathlib import Path
from string import Template
from types import SimpleNamespace
from typing import Any, Callable, ClassVar, List, Optional, Sequence, Union

from autogen_core import CancellationToken
from autogen_core.code_executor import CodeBlock, CodeExecutor, FunctionWithRequirements, FunctionWithRequirementsStr
from typing_extensions import ParamSpec

from .._common import (
    PYTHON_VARIANTS,
    CommandLineCodeResult,
    build_python_functions_file,
    get_file_name_from_content,
    lang_to_cmd,
    silence_pip,
    to_stub,
)

__all__ = ("LocalCommandLineCodeExecutor",)

A = ParamSpec("A")

class LocalCommandLineCodeExecutor(CodeExecutor):
    """A code executor class that executes code through a local command line
    environmen

Output: Code analysis and explanation


Instruction: Analyze this code content

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from ._azure_token_provider import AzureTokenProvider
from ._openai_client import (
    AzureOpenAIChatCompletionClient,
    OpenAIChatCompletionClient,
)
from .config import AzureOpenAIClientConfiguration, OpenAIClientConfiguration

__all__ = [
    "AzureOpenAIClientConfiguration",
    "AzureOpenAIChatCompletionClient",
    "OpenAIClientConfiguration",
    "OpenAIChatCompletionClient",
    "AzureTokenProvider",
]

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from typing import List

from autogen_core import Component
from azure.core.credentials import TokenProvider
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from pydantic import BaseModel
from typing_extensions import Self

class TokenProviderConfig(BaseModel):
    provider_kind: str
    scopes: List[str]

class AzureTokenProvider(Component[TokenProviderConfig]):
    component_type = "token_provider"
    component_config_schema = TokenProviderConfig
    component_provider_override = "autogen_ext.models.openai.AzureTokenProvider"

    def __init__(self, credential: TokenProvider, *scopes: str):
        self.credential = credential
        self.scopes = list(scopes)
        self.provider = get_bearer_token_provider(self.credential, *self.scopes)

    def __call__(self) -> str:
        return self.provider()

    def _to_config(self) -> TokenProviderConfig:
        """Dump the configuration that would be requite to create a new instance of a component matchi

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from typing import Dict

from autogen_core.models import ModelFamily, ModelInfo

# Based on: https://platform.openai.com/docs/models/continuous-model-upgrades
# This is a moving target, so correctness is checked by the model value returned by openai against expected values at runtime``
_MODEL_POINTERS = {
    "o1-preview": "o1-preview-2024-09-12",
    "o1-mini": "o1-mini-2024-09-12",
    "gpt-4o": "gpt-4o-2024-08-06",
    "gpt-4o-mini": "gpt-4o-mini-2024-07-18",
    "gpt-4-turbo": "gpt-4-turbo-2024-04-09",
    "gpt-4-turbo-preview": "gpt-4-0125-preview",
    "gpt-4": "gpt-4-0613",
    "gpt-4-32k": "gpt-4-32k-0613",
    "gpt-3.5-turbo": "gpt-3.5-turbo-0125",
    "gpt-3.5-turbo-16k": "gpt-3.5-turbo-16k-0613",
}

_MODEL_INFO: Dict[str, ModelInfo] = {
    "o1-preview-2024-09-12": {
        "vision": False,
        "function_calling": False,
        "json_output": False,
        "family": ModelFamily.O1,
    },
    "o1-mini-2024-09-12": {
        "vision": False,
        "function_calling":

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import asyncio
import inspect
import json
import logging
import math
import re
import warnings
from asyncio import Task
from typing import (
    Any,
    AsyncGenerator,
    Dict,
    List,
    Mapping,
    Optional,
    Sequence,
    Set,
    Type,
    Union,
    cast,
)

import tiktoken
from autogen_core import (
    EVENT_LOGGER_NAME,
    TRACE_LOGGER_NAME,
    CancellationToken,
    Component,
    FunctionCall,
    Image,
)
from autogen_core.logging import LLMCallEvent
from autogen_core.models import (
    AssistantMessage,
    ChatCompletionClient,
    ChatCompletionTokenLogprob,
    CreateResult,
    FunctionExecutionResultMessage,
    LLMMessage,
    ModelCapabilities,  # type: ignore
    ModelFamily,
    ModelInfo,
    RequestUsage,
    SystemMessage,
    TopLogprob,
    UserMessage,
)
from autogen_core.tools import Tool, ToolSchema
from openai import AsyncAzureOpenAI, AsyncOpenAI
from openai.types.chat import (
    ChatCompletion,
    ChatCompletionAssistantMessageParam,
    C

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from typing import Awaitable, Callable, Dict, List, Literal, Optional, Union

from autogen_core import ComponentModel
from autogen_core.models import ModelCapabilities, ModelInfo  # type: ignore
from pydantic import BaseModel
from typing_extensions import Required, TypedDict

from .._azure_token_provider import AzureTokenProvider

class ResponseFormat(TypedDict):
    type: Literal["text", "json_object"]

class CreateArguments(TypedDict, total=False):
    frequency_penalty: Optional[float]
    logit_bias: Optional[Dict[str, int]]
    max_tokens: Optional[int]
    n: Optional[int]
    presence_penalty: Optional[float]
    response_format: ResponseFormat
    seed: Optional[int]
    stop: Union[Optional[str], List[str]]
    temperature: Optional[float]
    top_p: Optional[float]
    user: str

AsyncAzureADTokenProvider = Callable[[], Union[str, Awaitable[str]]]

class BaseOpenAIClientConfiguration(CreateArguments, total=False):
    model: str
    api_key: str
    timeout: Union[float,

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from ._replay_chat_completion_client import ReplayChatCompletionClient

__all__ = [
    "ReplayChatCompletionClient",
]

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from __future__ import annotations

import logging
import warnings
from typing import Any, AsyncGenerator, List, Mapping, Optional, Sequence, Union

from autogen_core import EVENT_LOGGER_NAME, CancellationToken
from autogen_core.models import (
    ChatCompletionClient,
    CreateResult,
    LLMMessage,
    ModelCapabilities,  # type: ignore
    ModelFamily,
    ModelInfo,
    RequestUsage,
)
from autogen_core.tools import Tool, ToolSchema

logger = logging.getLogger(EVENT_LOGGER_NAME)

class ReplayChatCompletionClient(ChatCompletionClient):
    """
    A mock chat completion client that replays predefined responses using an index-based approach.

    This class simulates a chat completion client by replaying a predefined list of responses. It supports both single completion and streaming responses. The responses can be either strings or CreateResult objects. The client now uses an index-based approach to access the responses, allowing for resetting the state.

    .. note::
        T

Output: Code analysis and explanation


Instruction: Analyze this code content

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from ._worker_runtime import GrpcWorkerAgentRuntime
from ._worker_runtime_host import GrpcWorkerAgentRuntimeHost
from ._worker_runtime_host_servicer import GrpcWorkerAgentRuntimeHostServicer

try:
    import grpc  # type: ignore
except ImportError as e:
    raise ImportError(
        "To use the GRPC runtime the grpc extra must be installed. Run `pip install autogen-ext[grpc]`"
    ) from e

__all__ = [
    "GrpcWorkerAgentRuntime",
    "GrpcWorkerAgentRuntimeHost",
    "GrpcWorkerAgentRuntimeHostServicer",
]

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
GRPC_IMPORT_ERROR_STR = (
    "Distributed runtime features require additional dependencies. Install them with: pip install autogen-core[grpc]"
)

DATA_CONTENT_TYPE_ATTR = "datacontenttype"
DATA_SCHEMA_ATTR = "dataschema"
AGENT_SENDER_TYPE_ATTR = "agagentsendertype"
AGENT_SENDER_KEY_ATTR = "agagentsenderkey"
MESSAGE_KIND_ATTR = "agmsgkind"
MESSAGE_KIND_VALUE_PUBLISH = "publish"
MESSAGE_KIND_VALUE_RPC_REQUEST = "rpc_request"
MESSAGE_KIND_VALUE_RPC_RESPONSE = "rpc_response"
MESSAGE_KIND_VALUE_RPC_ERROR = "error"

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from typing import Any, Sequence, Tuple

# Had to redefine this from grpc.aio._typing as using that one was causing mypy errors
ChannelArgumentType = Sequence[Tuple[str, Any]]

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import asyncio
import inspect
import json
import logging
import signal
import uuid
import warnings
from asyncio import Future, Task
from collections import defaultdict
from typing import (
    TYPE_CHECKING,
    Any,
    AsyncIterable,
    AsyncIterator,
    Awaitable,
    Callable,
    ClassVar,
    DefaultDict,
    Dict,
    List,
    Literal,
    Mapping,
    ParamSpec,
    Sequence,
    Set,
    Type,
    TypeVar,
    cast,
)

from autogen_core import (
    JSON_DATA_CONTENT_TYPE,
    PROTOBUF_DATA_CONTENT_TYPE,
    Agent,
    AgentId,
    AgentInstantiationContext,
    AgentMetadata,
    AgentRuntime,
    AgentType,
    CancellationToken,
    MessageContext,
    MessageHandlerContext,
    MessageSerializer,
    Subscription,
    TopicId,
    TypePrefixSubscription,
    TypeSubscription,
)
from autogen_core._runtime_impl_helpers import SubscriptionManager, get_impl
from autogen_core._serialization import (
    SerializationRegistry,
)
from autogen_core._telemetry import MessageRunt

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import asyncio
import logging
import signal
from typing import Optional, Sequence

from ._constants import GRPC_IMPORT_ERROR_STR
from ._type_helpers import ChannelArgumentType
from ._worker_runtime_host_servicer import GrpcWorkerAgentRuntimeHostServicer

try:
    import grpc
except ImportError as e:
    raise ImportError(GRPC_IMPORT_ERROR_STR) from e
from .protos import agent_worker_pb2_grpc

logger = logging.getLogger("autogen_core")

class GrpcWorkerAgentRuntimeHost:
    def __init__(self, address: str, extra_grpc_config: Optional[ChannelArgumentType] = None) -> None:
        self._server = grpc.aio.server(options=extra_grpc_config)
        self._servicer = GrpcWorkerAgentRuntimeHostServicer()
        agent_worker_pb2_grpc.add_AgentRpcServicer_to_server(self._servicer, self._server)
        self._server.add_insecure_port(address)
        self._address = address
        self._serve_task: asyncio.Task[None] | None = None

    async def _serve(self) -> None:
        await self._server.

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import asyncio
import logging
from _collections_abc import AsyncIterator, Iterator
from asyncio import Future, Task
from typing import Any, Dict, Set, cast

from autogen_core import Subscription, TopicId, TypePrefixSubscription, TypeSubscription
from autogen_core._runtime_impl_helpers import SubscriptionManager

from ._constants import GRPC_IMPORT_ERROR_STR

try:
    import grpc
except ImportError as e:
    raise ImportError(GRPC_IMPORT_ERROR_STR) from e

from .protos import agent_worker_pb2, agent_worker_pb2_grpc, cloudevent_pb2

logger = logging.getLogger("autogen_core")
event_logger = logging.getLogger("autogen_core.events")

class GrpcWorkerAgentRuntimeHostServicer(agent_worker_pb2_grpc.AgentRpcServicer):
    """A gRPC servicer that hosts message delivery service for agents."""

    def __init__(self) -> None:
        self._client_id = 0
        self._client_id_lock = asyncio.Lock()
        self._send_queues: Dict[int, asyncio.Queue[agent_worker_pb2.Message]] = {}
        self._ag

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
"""
The :mod:`autogen_ext.runtimes.grpc.protos` module provides Google Protobuf classes for agent-worker communication
"""

import os
import sys

sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: agent_worker.proto
# Protobuf Python Version: 4.25.1
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder
# @@protoc_insertion_point(imports)

_sym_db = _symbol_database.Default()

import cloudevent_pb2 as cloudevent__pb2
from google.protobuf import any_pb2 as google_dot_protobuf_dot_any__pb2

DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x12\x61gent_worker.proto\x12\x06\x61gents\x1a\x10\x63loudevent.proto\x1a\x19google/protobuf/any.proto\"\'\n\x07TopicId\x12\x0c\n\x04type\x18\x01 \x01(\t\x12\x0e\n\x06source\x18\x02 \x01(\t\"$\n\x07\x41gentId\x12\x0c\n\x04type\x18\x01 \x01(\t\x12\x0b\n\x03key\x18\x02 \x01(\t\"E\n\x07Payload\x12\x11\n\tdata_type\x18\x01 \x0

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc

import agent_worker_pb2 as agent__worker__pb2

class AgentRpcStub(object):
    """Missing associated documentation comment in .proto file."""

    def __init__(self, channel):
        """Constructor.

        Args:
            channel: A grpc.Channel.
        """
        self.OpenChannel = channel.stream_stream(
                '/agents.AgentRpc/OpenChannel',
                request_serializer=agent__worker__pb2.Message.SerializeToString,
                response_deserializer=agent__worker__pb2.Message.FromString,
                )
        self.GetState = channel.unary_unary(
                '/agents.AgentRpc/GetState',
                request_serializer=agent__worker__pb2.AgentId.SerializeToString,
                response_deserializer=agent__worker__pb2.GetStateResponse.FromString,
                )
        self.SaveState = ch

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: cloudevent.proto
# Protobuf Python Version: 4.25.1
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder
# @@protoc_insertion_point(imports)

_sym_db = _symbol_database.Default()

from google.protobuf import any_pb2 as google_dot_protobuf_dot_any__pb2
from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2

DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x10\x63loudevent.proto\x12\x11io.cloudevents.v1\x1a\x19google/protobuf/any.proto\x1a\x1fgoogle/protobuf/timestamp.proto\"\xb0\x04\n\nCloudEvent\x12\n\n\x02id\x18\x01 \x01(\t\x12\x0e\n\x06source\x18\x02 \x01(\t\x12\x14\n\x0cspec_version\x18\x03 \x01(\t\x12\x0c\n\x04type\x18\x04 \x01

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc

Output: Code analysis and explanation


Instruction: Analyze this code content

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import warnings
from typing import List

from autogen_agentchat.agents import CodeExecutorAgent, UserProxyAgent
from autogen_agentchat.base import ChatAgent
from autogen_agentchat.teams import MagenticOneGroupChat
from autogen_core.models import ChatCompletionClient

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.code_executors.local import LocalCommandLineCodeExecutor
from autogen_ext.models.openai._openai_client import BaseOpenAIChatCompletionClient

class MagenticOne(MagenticOneGroupChat):
    """
    MagenticOne is a specialized group chat class that integrates various agents
    such as FileSurfer, WebSurfer, Coder, and Executor to solve complex tasks.
    To read more about the science behind Magentic-One, see the full blog post: `Magentic-One: A Generalist Multi-Agent System for Solving Complex Tasks <https://www.microsoft.com/e

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import argparse
import asyncio

from autogen_agentchat.ui import Console

from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_ext.teams.magentic_one import MagenticOne

def main() -> None:
    """
    Command-line interface for running a complex task using MagenticOne.

    This script accepts a single task string and an optional flag to disable
    human-in-the-loop mode. It initializes the necessary clients and runs the
    task using the MagenticOne class.

    Arguments:
    task (str): The task to be executed by MagenticOne.
    --no-hil: Optional flag to disable human-in-the-loop mode.

    Example usage:
    python magentic_one_cli.py "example task"
    python magentic_one_cli.py --no-hil "example task"
    """
    parser = argparse.ArgumentParser(
        description=(
            "Run a complex task using MagenticOne.\n\n"
            "For more information, refer to the following paper: https://arxiv.org/abs/2411.04468"
        )
    )
    parser.add

Output: Code analysis and explanation


Instruction: Analyze this code content

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from ._code_execution import CodeExecutionInput, CodeExecutionResult, PythonCodeExecutionTool

__all__ = ["CodeExecutionInput", "CodeExecutionResult", "PythonCodeExecutionTool"]

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from autogen_core import CancellationToken
from autogen_core.code_executor import CodeBlock, CodeExecutor
from autogen_core.tools import BaseTool
from pydantic import BaseModel, Field, model_serializer

class CodeExecutionInput(BaseModel):
    code: str = Field(description="The contents of the Python code block that should be executed")

class CodeExecutionResult(BaseModel):
    success: bool
    output: str

    @model_serializer
    def ser_model(self) -> str:
        return self.output

class PythonCodeExecutionTool(BaseTool[CodeExecutionInput, CodeExecutionResult]):
    def __init__(self, executor: CodeExecutor):
        super().__init__(CodeExecutionInput, CodeExecutionResult, "CodeExecutor", "Execute Python code blocks.")
        self._executor = executor

    async def run(self, args: CodeExecutionInput, cancellation_token: CancellationToken) -> CodeExecutionResult:
        code_blocks = [CodeBlock(code=args.code, language="python")]
        result = await self._executor.exec

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from ._langchain_adapter import LangChainToolAdapter

__all__ = ["LangChainToolAdapter"]

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from __future__ import annotations

import asyncio
import inspect
from typing import TYPE_CHECKING, Any, Callable, Dict, Type, cast

from autogen_core import CancellationToken
from autogen_core.tools import BaseTool
from pydantic import BaseModel, Field, create_model

if TYPE_CHECKING:
    from langchain_core.tools import BaseTool as LangChainTool

class LangChainToolAdapter(BaseTool[BaseModel, Any]):
    """Allows you to wrap a LangChain tool and make it available to AutoGen.

    .. note::

        This class requires the :code:`langchain` extra for the :code:`autogen-ext` package.

    Args:
        langchain_tool (LangChainTool): A LangChain tool to wrap

    Examples:

    Use the `PythonAstREPLTool` from the `langchain_experimental` package to
    create a tool that allows you to interact with a Pandas DataFrame.

        .. code-block:: python

            import asyncio
            import pandas as pd
            from langchain_experimental.tools.python.tool import PythonAstR

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import os
from enum import Enum
from typing import List, Literal, Optional, Union

import pytest
from autogen_agentchat.messages import TextMessage
from autogen_core import CancellationToken
from autogen_core.tools._base import BaseTool, Tool
from autogen_ext.agents.openai import OpenAIAssistantAgent
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from openai import AsyncAzureOpenAI
from pydantic import BaseModel

class QuestionType(str, Enum):
    MULTIPLE_CHOICE = "MULTIPLE_CHOICE"
    FREE_RESPONSE = "FREE_RESPONSE"

class Question(BaseModel):
    question_text: str
    question_type: QuestionType
    choices: Optional[List[str]] = None

class DisplayQuizArgs(BaseModel):
    title: str
    questions: List[Question]

class QuizResponses(BaseModel):
    responses: List[str]

class DisplayQuizTool(BaseTool[DisplayQuizArgs, QuizResponses]):
    def __init__(self) -> None:
        super().__init__(
            args_type=DisplayQuizArgs,
            retur

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import pytest
from autogen_ext.agents.web_surfer.playwright_controller import PlaywrightController
from playwright.async_api import async_playwright

FAKE_HTML = """
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fake Page</title>

Welcome to the Fake Page

    <button id="click-me">Click Me</button>
    <input type="text" id="input-box" />

"""

@pytest.mark.asyncio
async def test_playwright_controller_initialization() -> None:
    controller = PlaywrightController()
    assert controller.viewport_width == 1440
    assert controller.viewport_height == 900
    assert controller.animate_actions is False

@pytest.mark.asyncio
async def test_playwright_controller_visit_page() -> None:
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context()

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from typing import Optional, Type, cast

import pytest
from autogen_core import CancellationToken
from autogen_core.tools import Tool
from autogen_ext.tools.langchain import LangChainToolAdapter  # type: ignore
from langchain_core.callbacks.manager import AsyncCallbackManagerForToolRun, CallbackManagerForToolRun
from langchain_core.tools import BaseTool as LangChainTool
from langchain_core.tools import tool  # pyright: ignore
from pydantic import BaseModel, Field

@tool  # type: ignore
def add(a: int, b: int) -> int:
    """Add two numbers"""
    return a + b

class CalculatorInput(BaseModel):
    a: int = Field(description="first number")
    b: int = Field(description="second number")

class CustomCalculatorTool(LangChainTool):
    name: str = "Calculator"
    description: str = "useful for when you need to answer questions about math"
    args_schema: Type[BaseModel] = CalculatorInput
    return_direct: bool = True

    def _run(self, a: int, b: int, run_manager: Optional[Callbac

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import asyncio
import json
import logging
from datetime import datetime
from typing import Any, AsyncGenerator, List

import pytest
from autogen_agentchat import EVENT_LOGGER_NAME
from autogen_agentchat.messages import (
    MultiModalMessage,
    TextMessage,
)
from autogen_ext.agents.web_surfer import MultimodalWebSurfer
from autogen_ext.models.openai import OpenAIChatCompletionClient
from openai.resources.chat.completions import AsyncCompletions
from openai.types.chat.chat_completion import ChatCompletion, Choice
from openai.types.chat.chat_completion_chunk import ChatCompletionChunk
from openai.types.chat.chat_completion_message import ChatCompletionMessage
from openai.types.chat.chat_completion_message_tool_call import ChatCompletionMessageToolCall, Function
from openai.types.completion_usage import CompletionUsage
from pydantic import BaseModel

class FileLogHandler(logging.Handler):
    def __init__(self, filename: str) -> None:
        super().__init__()
        self.filename

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import asyncio
import logging
import os
from typing import Any, List

import pytest
from autogen_core import (
    PROTOBUF_DATA_CONTENT_TYPE,
    AgentId,
    AgentType,
    DefaultTopicId,
    MessageContext,
    RoutedAgent,
    Subscription,
    TopicId,
    TypeSubscription,
    default_subscription,
    event,
    try_get_known_serializers_for_type,
    type_subscription,
)
from autogen_ext.runtimes.grpc import GrpcWorkerAgentRuntime, GrpcWorkerAgentRuntimeHost
from autogen_test_utils import (
    CascadingAgent,
    CascadingMessageType,
    ContentMessage,
    LoopbackAgent,
    LoopbackAgentWithDefaultSubscription,
    MessageType,
    NoopAgent,
)
from protos.serialization_test_pb2 import ProtoMessage

@pytest.mark.asyncio
async def test_agent_types_must_be_unique_single_worker() -> None:
    host_address = "localhost:50051"
    host = GrpcWorkerAgentRuntimeHost(address=host_address)
    host.start()

    worker = GrpcWorkerAgentRuntime(host_address=host_address)
    worker.

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# File based from: https://github.com/microsoft/autogen/blob/main/test/coding/test_commandline_code_executor.py
# Credit to original authors

import asyncio
import os
import sys
import tempfile

import pytest
from anyio import open_file
from autogen_core import CancellationToken
from autogen_core.code_executor import CodeBlock
from autogen_ext.code_executors.azure import ACADynamicSessionsCodeExecutor
from azure.identity import DefaultAzureCredential

UNIX_SHELLS = ["bash", "sh", "shell"]
WINDOWS_SHELLS = ["ps1", "pwsh", "powershell"]
PYTHON_VARIANTS = ["python", "Python", "py"]

ENVIRON_KEY_AZURE_POOL_ENDPOINT = "AZURE_POOL_ENDPOINT"

POOL_ENDPOINT = os.getenv(ENVIRON_KEY_AZURE_POOL_ENDPOINT)

@pytest.mark.skipif(
    not POOL_ENDPOINT,
    reason="do not run if pool endpoint is not defined",
)
@pytest.mark.asyncio
async def test_execute_code() -> None:
    assert POOL_ENDPOINT is not None
    cancellation_token = CancellationToken()
    executor = ACADynamicSessionsCodeExecutor(

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# File based from: https://github.com/microsoft/autogen/blob/main/test/coding/test_user_defined_functions.py
# Credit to original authors

import os

import polars
import pytest
from autogen_core import CancellationToken
from autogen_core.code_executor import (
    CodeBlock,
    FunctionWithRequirements,
    with_requirements,
)
from autogen_ext.code_executors.azure import ACADynamicSessionsCodeExecutor
from azure.identity import DefaultAzureCredential

ENVIRON_KEY_AZURE_POOL_ENDPOINT = "AZURE_POOL_ENDPOINT"

DUMMY_POOL_ENDPOINT = "DUMMY_POOL_ENDPOINT"
POOL_ENDPOINT = os.getenv(ENVIRON_KEY_AZURE_POOL_ENDPOINT)

def add_two_numbers(a: int, b: int) -> int:
    """Add two numbers together."""
    return a + b

@with_requirements(python_packages=["polars"], global_imports=["polars"])
def load_data() -> polars.DataFrame:
    """Load some sample data.

    Returns:
        polars.DataFrame: A DataFrame with the following columns: name(str), location(str), age(int)
    """
    data = {

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# File based from: https://github.com/microsoft/autogen/blob/main/test/coding/test_commandline_code_executor.py
# Credit to original authors

import asyncio
import os
import shutil
import sys
import tempfile
import venv
from pathlib import Path
from typing import AsyncGenerator, TypeAlias

import pytest
import pytest_asyncio
from aiofiles import open
from autogen_core import CancellationToken
from autogen_core.code_executor import CodeBlock
from autogen_ext.code_executors.local import LocalCommandLineCodeExecutor

@pytest_asyncio.fixture(scope="function")  # type: ignore
async def executor_and_temp_dir(
    request: pytest.FixtureRequest,
) -> AsyncGenerator[tuple[LocalCommandLineCodeExecutor, str], None]:
    with tempfile.TemporaryDirectory() as temp_dir:
        yield LocalCommandLineCodeExecutor(work_dir=temp_dir), temp_dir

ExecutorFixture: TypeAlias = tuple[LocalCommandLineCodeExecutor, str]

@pytest.mark.asyncio
@pytest.mark.parametrize("executor_and_temp_dir", ["local"], ind

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# mypy: disable-error-code="no-any-unimported"
import os
import sys
import tempfile
from pathlib import Path
from typing import AsyncGenerator, TypeAlias

import pytest
import pytest_asyncio
from aiofiles import open
from autogen_core import CancellationToken
from autogen_core.code_executor import CodeBlock
from autogen_ext.code_executors.docker import DockerCommandLineCodeExecutor

def docker_tests_enabled() -> bool:
    if os.environ.get("SKIP_DOCKER", "unset").lower() == "true":
        return False

    try:
        import docker
        from docker.errors import DockerException
    except ImportError:
        return False

    try:
        client = docker.from_env()
        client.ping()  # type: ignore
        return True
    except DockerException:
        return False

@pytest_asyncio.fixture(scope="function")  # type: ignore
async def executor_and_temp_dir(
    request: pytest.FixtureRequest,
) -> AsyncGenerator[tuple[DockerCommandLineCodeExecutor, str], None]:
    if not do

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# File based from: https://github.com/microsoft/autogen/blob/main/test/coding/test_user_defined_functions.py
# Credit to original authors

import os
import tempfile

import polars
import pytest
from autogen_core import CancellationToken
from autogen_core.code_executor import (
    CodeBlock,
    FunctionWithRequirements,
    with_requirements,
)
from autogen_ext.code_executors.local import LocalCommandLineCodeExecutor

ENVIRON_KEY_AZURE_POOL_ENDPOINT = "AZURE_POOL_ENDPOINT"

DUMMY_POOL_ENDPOINT = "DUMMY_POOL_ENDPOINT"
POOL_ENDPOINT = os.getenv(ENVIRON_KEY_AZURE_POOL_ENDPOINT)

def add_two_numbers(a: int, b: int) -> int:
    """Add two numbers together."""
    return a + b

@with_requirements(python_packages=["polars"], global_imports=["polars"])
def load_data() -> polars.DataFrame:
    """Load some sample data.

    Returns:
        polars.DataFrame: A DataFrame with the following columns: name(str), location(str), age(int)
    """
    data = {
        "name": ["John", "Anna", "Peter

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import asyncio
from typing import Annotated, Any, AsyncGenerator, List, Tuple
from unittest.mock import MagicMock

import pytest
from autogen_core import CancellationToken, Image
from autogen_core.models import (
    AssistantMessage,
    CreateResult,
    FunctionExecutionResult,
    FunctionExecutionResultMessage,
    LLMMessage,
    RequestUsage,
    SystemMessage,
    UserMessage,
)
from autogen_core.models._model_client import ModelFamily
from autogen_core.tools import BaseTool, FunctionTool
from autogen_ext.models.openai import AzureOpenAIChatCompletionClient, OpenAIChatCompletionClient
from autogen_ext.models.openai._model_info import resolve_model
from autogen_ext.models.openai._openai_client import calculate_vision_tokens, convert_tools
from openai.resources.chat.completions import AsyncCompletions
from openai.types.chat.chat_completion import ChatCompletion, Choice
from openai.types.chat.chat_completion_chunk import ChatCompletionChunk, ChoiceDelta
from openai.types.chat.chat

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import copy
from dataclasses import dataclass
from typing import List

import pytest
from autogen_core import (
    AgentId,
    DefaultTopicId,
    MessageContext,
    RoutedAgent,
    SingleThreadedAgentRuntime,
    default_subscription,
    message_handler,
)
from autogen_core.models import ChatCompletionClient, CreateResult, SystemMessage, UserMessage
from autogen_ext.models.replay import ReplayChatCompletionClient

@dataclass
class ContentMessage:
    content: str

class LLMAgent(RoutedAgent):
    def __init__(self, model_client: ChatCompletionClient) -> None:
        super().__init__("LLM Agent!")
        self._chat_history: List[ContentMessage] = []
        self._model_client = model_client
        self.num_calls = 0

    @message_handler
    async def on_new_message(self, message: ContentMessage, ctx: MessageContext) -> None:
        self._chat_history.append(message)
        self.num_calls += 1
        completion = await self._model_client.create(messages=self._fixed_message

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: serialization_test.proto
# Protobuf Python Version: 4.25.1
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder

# @@protoc_insertion_point(imports)

_sym_db = _symbol_database.Default()

DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x18serialization_test.proto\x12\x06\x61gents"\x1f\n\x0cProtoMessage\x12\x0f\n\x07message\x18\x01 \x01(\t"L\n\x13NestingProtoMessage\x12\x0f\n\x07message\x18\x01 \x01(\t\x12$\n\x06nested\x18\x02 \x01(\x0b\x32\x14.agents.ProtoMessageb\x06proto3')

_globals = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "serialization_test_pb2", _globals)
if _descript

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc

Output: Code analysis and explanation


Instruction: Analyze this document content

Input:
# Magentic-One

> [!IMPORTANT]
> **Note (December 22nd, 2024):** We recommend using the [Magentic-One API](https://github.com/microsoft/autogen/tree/main/python/packages/autogen-ext/src/autogen_ext/teams/magentic_one.py) as the preferred way to interact with Magentic-One. The API provides a more streamlined and robust interface for integrating Magentic-One into your projects.

> [!CAUTION]
> Using Magentic-One involves interacting with a digital world designed for humans, which carries inherent risks. To minimize these risks, consider the following precautions:
>
> 1. **Use Containers**: Run all tasks in docker containers to isolate the agents and prevent direct system attacks.
> 2. **Virtual Environment**: Use a virtual environment to run the agents and prevent them from accessing sensitive data.
> 3. **Monitor Logs**: Closely monitor logs during and after execution to detect and mitigate risky behavior.
> 4. **Human Oversight**: Run the examples with a human in the loop to supervise

Output: Document summary and key points


Instruction: Analyze this document content

Input:
# Examples of Magentic-One

**Note**: The examples in this folder are ran at your own risk. They involve agents navigating the web, executing code and browsing local files. Please supervise the execution of the agents to reduce any risks. We also recommend running the examples in a virtual machine or a sandboxed environment.

We include various examples for using Magentic-One and is agents:

- [example.py](example.py): Is [human-in-the-loop] Magentic-One trying to solve a task specified by user input.

    ```bash

    # Specify logs directory
    python examples/example.py --logs_dir ./my_logs

    # Enable human-in-the-loop mode
    python examples/example.py -logs_dir ./my_logs --hil_mode

    # Save screenshots of browser
    python examples/example.py -logs_dir ./my_logs --save_screenshots
    ```

    Arguments:

    - logs_dir: (Required) Directory for logs, downloads and screenshots of browser (default: current directory)
    - hil_mode: (Optional) Enable human-in-the-loop

Output: Document summary and key points


Instruction: Analyze this code content

Input:
"""This example demonstrates MagenticOne performing a task given by the user and returning a final answer."""

import argparse
import asyncio
import logging
import os

from autogen_core import EVENT_LOGGER_NAME, AgentId, AgentProxy, SingleThreadedAgentRuntime
from autogen_core.code_executor import CodeBlock
from autogen_ext.code_executors.docker import DockerCommandLineCodeExecutor
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 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 confirm_code(code: CodeBlock) -> bool:
    respon

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
"""This example demonstrates a human user interacting with a coder agent and a executor agent
to generate and execute code snippets. The user and the agents take turn sequentially
to write input, generate code snippets and execute them, orchestrated by an
round-robin orchestrator agent. The code snippets are executed inside a docker container.
"""

import asyncio
import logging

from autogen_core import EVENT_LOGGER_NAME, AgentId, AgentProxy, SingleThreadedAgentRuntime
from autogen_core.code_executor import CodeBlock
from autogen_ext.code_executors.docker import DockerCommandLineCodeExecutor
from autogen_magentic_one.agents.coder import Coder, Executor
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

async def confirm_code(code: CodeBlock) -> bool:

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
"""This example demonstrates a human user interacting with a file surfer agent
to navigate the file system. The human user and the file surfer agent takes turn
to write input or perform actions, orchestrated by an round-robin orchestrator agent."""

import asyncio
import logging

from autogen_core import EVENT_LOGGER_NAME, AgentId, AgentProxy, SingleThreadedAgentRuntime
from autogen_magentic_one.agents.file_surfer import FileSurfer
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

async def main() -> None:
    # Create the runtime.
    runtime = SingleThreadedAgentRuntime()

    # Get an appropriate client
    client = create_completion_client_from_env()

    # Register agents.
    await FileSurfer.register(runtime, "file_surfer", lambda: FileSurfer(mode

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
"""This example demonstrates a human user interacting with a coder agent
which uses a model to generate code snippets. The user and the coder agent
takes turn to write input or generate code snippets, orchestrated by an
round-robin orchestrator agent.
The code snippets are not executed in this example."""

import asyncio
import logging

from autogen_core import EVENT_LOGGER_NAME, AgentId, AgentProxy, SingleThreadedAgentRuntime

# from typing import Any, Dict, List, Tuple, Union
from autogen_magentic_one.agents.coder import Coder
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

async def main() -> None:
    # Create the runtime.
    runtime = SingleThreadedAgentRuntime()

    # Get an appropriate client
    client = create_completion_client_from_env()

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
"""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

Output: Code analysis and explanation


Instruction: Analyze this document content

Input:
# 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

Output: Document summary and key points


Instruction: Analyze this code content

Input:
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.

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
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

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
import importlib.metadata

ABOUT = "This is Magentic-One."

__version__ = importlib.metadata.version("autogen_magentic_one")

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
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 =

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
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

Output: Code analysis and explanation


Instruction: Analyze this code content

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
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

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
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

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
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

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
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

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
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

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
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

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
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} ")

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from .file_surfer import FileSurfer

__all__ = ["FileSurfer"]

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
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

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
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,

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
from .multimodal_web_surfer import MultimodalWebSurfer

__all__ = ("MultimodalWebSurfer",)

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
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

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
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

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
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

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
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

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
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",
)

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
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

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
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

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# 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:

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
# 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

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
#!/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()

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
#!/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

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
#!/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

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
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"
}
"""

Output: Code analysis and explanation


Instruction: Analyze this code content

Input:
#!/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

Output: Code analysis and explanation