instruction
stringclasses 2
values | input
stringlengths 0
1k
| output
stringclasses 2
values | metadata
dict |
---|---|---|---|
Analyze this code content | from ._caller_loop import tool_agent_caller_loop
from ._tool_agent import (
InvalidToolArgumentsException,
ToolAgent,
ToolException,
ToolExecutionException,
ToolNotFoundException,
)
__all__ = [
"ToolAgent",
"ToolException",
"ToolNotFoundException",
"InvalidToolArgumentsException",
"ToolExecutionException",
"tool_agent_caller_loop",
]
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/src/autogen_core/tool_agent/__init__.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | import asyncio
from typing import List
from .. import AgentId, AgentRuntime, BaseAgent, CancellationToken, FunctionCall
from ..models import (
AssistantMessage,
ChatCompletionClient,
FunctionExecutionResult,
FunctionExecutionResultMessage,
LLMMessage,
)
from ..tools import Tool, ToolSchema
from ._tool_agent import ToolException
async def tool_agent_caller_loop(
caller: BaseAgent | AgentRuntime,
tool_agent_id: AgentId,
model_client: ChatCompletionClient,
input_messages: List[LLMMessage],
tool_schema: List[ToolSchema] | List[Tool],
cancellation_token: CancellationToken | None = None,
caller_source: str = "assistant",
) -> List[LLMMessage]:
"""Start a caller loop for a tool agent. This function sends messages to the tool agent
and the model client in an alternating fashion until the model client stops generating tool calls.
Args:
tool_agent_id (AgentId): The Agent ID of the tool agent.
input_messages (List[LLM | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/src/autogen_core/tool_agent/_caller_loop.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | import json
from dataclasses import dataclass
from typing import List
from .. import FunctionCall, MessageContext, RoutedAgent, message_handler
from ..models import FunctionExecutionResult
from ..tools import Tool
__all__ = [
"ToolAgent",
"ToolException",
"ToolNotFoundException",
"InvalidToolArgumentsException",
"ToolExecutionException",
]
@dataclass
class ToolException(BaseException):
call_id: str
content: str
@dataclass
class ToolNotFoundException(ToolException):
pass
@dataclass
class InvalidToolArgumentsException(ToolException):
pass
@dataclass
class ToolExecutionException(ToolException):
pass
class ToolAgent(RoutedAgent):
"""A tool agent accepts direct messages of the type `FunctionCall`,
executes the requested tool with the provided arguments, and returns the
result as `FunctionExecutionResult` messages.
Args:
description (str): The description of the agent.
tools (List[Tool]): The list of tools t | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/src/autogen_core/tool_agent/_tool_agent.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | from ._base import BaseTool, BaseToolWithState, ParametersSchema, Tool, ToolSchema
from ._function_tool import FunctionTool
__all__ = [
"Tool",
"ToolSchema",
"ParametersSchema",
"BaseTool",
"BaseToolWithState",
"FunctionTool",
]
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/src/autogen_core/tools/__init__.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | import json
from abc import ABC, abstractmethod
from collections.abc import Sequence
from typing import Any, Dict, Generic, Mapping, Protocol, Type, TypedDict, TypeVar, cast, runtime_checkable
import jsonref
from pydantic import BaseModel
from typing_extensions import NotRequired
from .. import CancellationToken
from .._function_utils import normalize_annotated_type
T = TypeVar("T", bound=BaseModel, contravariant=True)
class ParametersSchema(TypedDict):
type: str
properties: Dict[str, Any]
required: NotRequired[Sequence[str]]
class ToolSchema(TypedDict):
parameters: NotRequired[ParametersSchema]
name: str
description: NotRequired[str]
@runtime_checkable
class Tool(Protocol):
@property
def name(self) -> str: ...
@property
def description(self) -> str: ...
@property
def schema(self) -> ToolSchema: ...
def args_type(self) -> Type[BaseModel]: ...
def return_type(self) -> Type[Any]: ...
def state_type(self) -> Type[Ba | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/src/autogen_core/tools/_base.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | import asyncio
import functools
from typing import Any, Callable
from pydantic import BaseModel
from .. import CancellationToken
from .._function_utils import (
args_base_model_from_signature,
get_typed_signature,
)
from ._base import BaseTool
class FunctionTool(BaseTool[BaseModel, BaseModel]):
"""
Create custom tools by wrapping standard Python functions.
`FunctionTool` offers an interface for executing Python functions either asynchronously or synchronously.
Each function must include type annotations for all parameters and its return type. These annotations
enable `FunctionTool` to generate a schema necessary for input validation, serialization, and for informing
the LLM about expected parameters. When the LLM prepares a function call, it leverages this schema to
generate arguments that align with the function's specifications.
.. note::
It is the user's responsibility to verify that the tool's output type matches the expected t | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/src/autogen_core/tools/_function_tool.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | import pytest
from autogen_core import AgentId, AgentInstantiationContext, AgentRuntime
from autogen_test_utils import NoopAgent
from pytest_mock import MockerFixture
@pytest.mark.asyncio
async def test_base_agent_create(mocker: MockerFixture) -> None:
runtime = mocker.Mock(spec=AgentRuntime)
# Shows how to set the context for the agent instantiation in a test context
with AgentInstantiationContext.populate_context((runtime, AgentId("name", "namespace"))):
agent = NoopAgent()
assert agent.runtime == runtime
assert agent.id == AgentId("name", "namespace")
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/tests/test_base_agent.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | import asyncio
from dataclasses import dataclass
import pytest
from autogen_core import (
AgentId,
AgentInstantiationContext,
CancellationToken,
MessageContext,
RoutedAgent,
SingleThreadedAgentRuntime,
message_handler,
)
@dataclass
class MessageType: ...
# Note for future reader:
# To do cancellation, only the token should be interacted with as a user
# If you cancel a future, it may not work as you expect.
class LongRunningAgent(RoutedAgent):
def __init__(self) -> None:
super().__init__("A long running agent")
self.called = False
self.cancelled = False
@message_handler
async def on_new_message(self, message: MessageType, ctx: MessageContext) -> MessageType:
self.called = True
sleep = asyncio.ensure_future(asyncio.sleep(100))
ctx.cancellation_token.link_future(sleep)
try:
await sleep
return MessageType()
except asyncio.CancelledError:
self. | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/tests/test_cancellation.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | import asyncio
from dataclasses import dataclass
import pytest
from autogen_core import (
ClosureAgent,
ClosureContext,
DefaultSubscription,
DefaultTopicId,
MessageContext,
SingleThreadedAgentRuntime,
)
@dataclass
class Message:
content: str
@pytest.mark.asyncio
async def test_register_receives_publish() -> None:
runtime = SingleThreadedAgentRuntime()
queue = asyncio.Queue[tuple[str, str]]()
async def log_message(closure_ctx: ClosureContext, message: Message, ctx: MessageContext) -> None:
key = closure_ctx.id.key
await queue.put((key, message.content))
await ClosureAgent.register_closure(runtime, "name", log_message, subscriptions=lambda: [DefaultSubscription()])
runtime.start()
await runtime.publish_message(Message("first message"), topic_id=DefaultTopicId())
await runtime.publish_message(Message("second message"), topic_id=DefaultTopicId())
await runtime.publish_message(Message("third message"), topi | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/tests/test_closure_agent.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | import textwrap
import pytest
from autogen_core.code_executor import (
Alias,
FunctionWithRequirements,
FunctionWithRequirementsStr,
ImportFromModule,
)
from autogen_core.code_executor._func_with_reqs import build_python_functions_file
from pandas import DataFrame, concat
def template_function() -> DataFrame: # type: ignore
data1 = {
"name": ["John", "Anna"],
"location": ["New York", "Paris"],
"age": [24, 13],
}
data2 = {
"name": ["Peter", "Linda"],
"location": ["Berlin", "London"],
"age": [53, 33],
}
df1 = DataFrame.from_dict(data1) # type: ignore
df2 = DataFrame.from_dict(data2) # type: ignore
return concat([df1, df2]) # type: ignore
@pytest.mark.asyncio
async def test_hashability_Import() -> None:
function = FunctionWithRequirements.from_callable( # type: ignore
template_function,
["pandas"],
[ImportFromModule("pandas", ["DataFrame", "concat"])],
)
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/tests/test_code_executor.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | from __future__ import annotations
import json
from typing import Any, Dict
import pytest
from autogen_core import Component, ComponentLoader, ComponentModel
from autogen_core._component_config import _type_to_provider_str # type: ignore
from autogen_core.models import ChatCompletionClient
from autogen_test_utils import MyInnerComponent, MyOuterComponent
from pydantic import BaseModel, ValidationError
from typing_extensions import Self
class MyConfig(BaseModel):
info: str
class MyComponent(Component[MyConfig]):
component_config_schema = MyConfig
component_type = "custom"
def __init__(self, info: str) -> None:
self.info = info
def _to_config(self) -> MyConfig:
return MyConfig(info=self.info)
@classmethod
def _from_config(cls, config: MyConfig) -> MyComponent:
return cls(info=config.info)
def test_custom_component() -> None:
comp = MyComponent("test")
comp2 = MyComponent.load_component(comp.dump_component())
asse | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/tests/test_component_config.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | import pytest
from autogen_core import AgentId, DefaultInterventionHandler, DropMessage, SingleThreadedAgentRuntime
from autogen_core.exceptions import MessageDroppedException
from autogen_test_utils import LoopbackAgent, MessageType
@pytest.mark.asyncio
async def test_intervention_count_messages() -> None:
class DebugInterventionHandler(DefaultInterventionHandler):
def __init__(self) -> None:
self.num_messages = 0
async def on_send(self, message: MessageType, *, sender: AgentId | None, recipient: AgentId) -> MessageType:
self.num_messages += 1
return message
handler = DebugInterventionHandler()
runtime = SingleThreadedAgentRuntime(intervention_handlers=[handler])
await LoopbackAgent.register(runtime, "name", LoopbackAgent)
loopback = AgentId("name", key="default")
runtime.start()
_response = await runtime.send_message(MessageType(), recipient=loopback)
await runtime.stop()
assert handler.num | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/tests/test_intervention.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | from typing import List
import pytest
from autogen_core.model_context import (
BufferedChatCompletionContext,
HeadAndTailChatCompletionContext,
UnboundedChatCompletionContext,
)
from autogen_core.models import AssistantMessage, LLMMessage, UserMessage
@pytest.mark.asyncio
async def test_buffered_model_context() -> None:
model_context = BufferedChatCompletionContext(buffer_size=2)
messages: List[LLMMessage] = [
UserMessage(content="Hello!", source="user"),
AssistantMessage(content="What can I do for you?", source="assistant"),
UserMessage(content="Tell what are some fun things to do in seattle.", source="user"),
]
await model_context.add_message(messages[0])
await model_context.add_message(messages[1])
await model_context.add_message(messages[2])
retrieved = await model_context.get_messages()
assert len(retrieved) == 2
assert retrieved[0] == messages[1]
assert retrieved[1] == messages[2]
await model_con | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/tests/test_model_context.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | import logging
from dataclasses import dataclass
from typing import Callable, cast
import pytest
from autogen_core import (
AgentId,
MessageContext,
RoutedAgent,
SingleThreadedAgentRuntime,
TopicId,
TypeSubscription,
event,
message_handler,
rpc,
)
from autogen_test_utils import LoopbackAgent
@dataclass
class UnhandledMessageType: ...
@dataclass
class MessageType: ...
class CounterAgent(RoutedAgent):
def __init__(self) -> None:
super().__init__("A loop back agent.")
self.num_calls_rpc = 0
self.num_calls_broadcast = 0
@message_handler(match=lambda _, ctx: ctx.is_rpc)
async def on_rpc_message(self, message: MessageType, ctx: MessageContext) -> MessageType:
self.num_calls_rpc += 1
return message
@message_handler(match=lambda _, ctx: not ctx.is_rpc)
async def on_broadcast_message(self, message: MessageType, ctx: MessageContext) -> None:
self.num_calls_broadcast += 1
@pytest.mar | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/tests/test_routed_agent.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | import logging
import pytest
from autogen_core import (
AgentId,
AgentInstantiationContext,
AgentType,
DefaultTopicId,
SingleThreadedAgentRuntime,
TopicId,
TypeSubscription,
try_get_known_serializers_for_type,
type_subscription,
)
from autogen_test_utils import (
CascadingAgent,
CascadingMessageType,
LoopbackAgent,
LoopbackAgentWithDefaultSubscription,
MessageType,
NoopAgent,
)
from autogen_test_utils.telemetry_test_utils import MyTestExporter, get_test_tracer_provider
from opentelemetry.sdk.trace import TracerProvider
test_exporter = MyTestExporter()
@pytest.fixture
def tracer_provider() -> TracerProvider:
test_exporter.clear()
return get_test_tracer_provider(test_exporter)
@pytest.mark.asyncio
async def test_agent_type_must_be_unique() -> None:
runtime = SingleThreadedAgentRuntime()
def agent_factory() -> NoopAgent:
id = AgentInstantiationContext.current_agent_id()
assert id == AgentId( | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/tests/test_runtime.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | from dataclasses import dataclass
from typing import Union
import pytest
from autogen_core import Image
from autogen_core._serialization import (
JSON_DATA_CONTENT_TYPE,
PROTOBUF_DATA_CONTENT_TYPE,
DataclassJsonMessageSerializer,
MessageSerializer,
PydanticJsonMessageSerializer,
SerializationRegistry,
try_get_known_serializers_for_type,
)
from PIL import Image as PILImage
from protos.serialization_test_pb2 import NestingProtoMessage, ProtoMessage
from pydantic import BaseModel
class PydanticMessage(BaseModel):
message: str
class NestingPydanticMessage(BaseModel):
message: str
nested: PydanticMessage
@dataclass
class DataclassMessage:
message: str
@dataclass
class NestingDataclassMessage:
message: str
nested: DataclassMessage
@dataclass
class NestingPydanticDataclassMessage:
message: str
nested: PydanticMessage
def test_pydantic() -> None:
serde = SerializationRegistry()
serde.add_serializer(try_get_known_s | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/tests/test_serialization.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | from typing import Any, Mapping
import pytest
from autogen_core import AgentId, BaseAgent, MessageContext, SingleThreadedAgentRuntime
class StatefulAgent(BaseAgent):
def __init__(self) -> None:
super().__init__("A stateful agent")
self.state = 0
async def on_message_impl(self, message: Any, ctx: MessageContext) -> None:
raise NotImplementedError
async def save_state(self) -> Mapping[str, Any]:
return {"state": self.state}
async def load_state(self, state: Mapping[str, Any]) -> None:
self.state = state["state"]
@pytest.mark.asyncio
async def test_agent_can_save_state() -> None:
runtime = SingleThreadedAgentRuntime()
await StatefulAgent.register(runtime, "name1", StatefulAgent)
agent1_id = AgentId("name1", key="default")
agent1: StatefulAgent = await runtime.try_get_underlying_agent_instance(agent1_id, type=StatefulAgent)
assert agent1.state == 0
agent1.state = 1
assert agent1.state == 1
age | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/tests/test_state.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | import pytest
from autogen_core import (
AgentId,
DefaultSubscription,
DefaultTopicId,
SingleThreadedAgentRuntime,
TopicId,
TypeSubscription,
)
from autogen_core.exceptions import CantHandleException
from autogen_test_utils import LoopbackAgent, MessageType
def test_type_subscription_match() -> None:
sub = TypeSubscription(topic_type="t1", agent_type="a1")
assert sub.is_match(TopicId(type="t0", source="s1")) is False
assert sub.is_match(TopicId(type="t1", source="s1")) is True
assert sub.is_match(TopicId(type="t1", source="s2")) is True
def test_type_subscription_map() -> None:
sub = TypeSubscription(topic_type="t1", agent_type="a1")
assert sub.map_to_agent(TopicId(type="t1", source="s1")) == AgentId(type="a1", key="s1")
with pytest.raises(CantHandleException):
_agent_id = sub.map_to_agent(TopicId(type="t0", source="s1"))
@pytest.mark.asyncio
async def test_non_default_default_subscription() -> None:
runtime = Sin | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/tests/test_subscription.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/tests/test_tool_agent.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/tests/test_tools.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/tests/test_types.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | # -*- 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/tests/protos/serialization_test_pb2.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/tests/protos/serialization_test_pb2_grpc.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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], / | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-core/tests/regressions/test_clean_terminate.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this document content | # autogen-ext
| Document summary and key points | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/README.md",
"file_type": ".md",
"source_type": "document"
} |
Analyze this code content | import importlib.metadata
__version__ = importlib.metadata.version("autogen_ext")
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/__init__.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | from ._file_surfer import FileSurfer
__all__ = ["FileSurfer"]
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/agents/file_surfer/__init__.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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- | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/agents/file_surfer/_file_surfer.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | # 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
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/agents/file_surfer/_markdown_file_browser.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/agents/file_surfer/_tool_definitions.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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"]
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/agents/magentic_one/__init__.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/agents/magentic_one/_magentic_one_coder_agent.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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"]
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/agents/openai/__init__.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/agents/openai/_openai_assistant_agent.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | from ._video_surfer import VideoSurfer
__all__ = ["VideoSurfer"]
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/agents/video_surfer/__init__.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/agents/video_surfer/_video_surfer.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/agents/video_surfer/tools.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | from ._multimodal_web_surfer import MultimodalWebSurfer
from .playwright_controller import PlaywrightController
__all__ = ["MultimodalWebSurfer", "PlaywrightController"]
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/agents/web_surfer/__init__.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/agents/web_surfer/_events.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/agents/web_surfer/_multimodal_web_surfer.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/agents/web_surfer/_prompts.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | import io
import random
from typing import BinaryIO, Dict, List, Tuple, cast
from PIL import Image, ImageDraw, ImageFont
from ._types import DOMRectangle, InteractiveRegion
TOP_NO_LABEL_ZONE = 20 # Don't print any labels close the top of the page
def add_set_of_mark(
screenshot: bytes | Image.Image | io.BufferedIOBase, ROIs: Dict[str, InteractiveRegion]
) -> Tuple[Image.Image, List[str], List[str], List[str]]:
if isinstance(screenshot, Image.Image):
return _add_set_of_mark(screenshot, ROIs)
if isinstance(screenshot, bytes):
screenshot = io.BytesIO(screenshot)
# TODO: Not sure why this cast was needed, but by this point screenshot is a binary file-like object
image = Image.open(cast(BinaryIO, screenshot))
comp, visible_rects, rects_above, rects_below = _add_set_of_mark(image, ROIs)
image.close()
return comp, visible_rects, rects_above, rects_below
def _add_set_of_mark(
screenshot: Image.Image, ROIs: Dict[str, InteractiveRegio | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/agents/web_surfer/_set_of_mark.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/agents/web_surfer/_tool_definitions.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/agents/web_surfer/_types.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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.")
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/agents/web_surfer/_utils.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/agents/web_surfer/playwright_controller.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/code_executors/_common.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | from ._azure_container_code_executor import ACADynamicSessionsCodeExecutor, TokenProvider
__all__ = ["TokenProvider", "ACADynamicSessionsCodeExecutor"]
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/code_executors/azure/__init__.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | # 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/code_executors/azure/_azure_container_code_executor.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | from ._docker_code_executor import DockerCommandLineCodeExecutor
__all__ = ["DockerCommandLineCodeExecutor"]
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/code_executors/docker/__init__.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | # 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/code_executors/docker/_docker_code_executor.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | # 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/code_executors/local/__init__.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/models/__init__.py",
"file_type": ".py",
"source_type": "code"
} |
|
Analyze this code content | from ._azure_token_provider import AzureTokenProvider
from ._openai_client import (
AzureOpenAIChatCompletionClient,
OpenAIChatCompletionClient,
)
from .config import AzureOpenAIClientConfiguration, OpenAIClientConfiguration
__all__ = [
"AzureOpenAIClientConfiguration",
"AzureOpenAIChatCompletionClient",
"OpenAIClientConfiguration",
"OpenAIChatCompletionClient",
"AzureTokenProvider",
]
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/models/openai/__init__.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/models/openai/_azure_token_provider.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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": | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/models/openai/_model_info.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/models/openai/_openai_client.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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, | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/models/openai/config/__init__.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | from ._replay_chat_completion_client import ReplayChatCompletionClient
__all__ = [
"ReplayChatCompletionClient",
]
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/models/replay/__init__.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/models/replay/_replay_chat_completion_client.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/runtimes/__init__.py",
"file_type": ".py",
"source_type": "code"
} |
|
Analyze this code content | 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",
]
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/runtimes/grpc/__init__.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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"
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/runtimes/grpc/_constants.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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]]
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/runtimes/grpc/_type_helpers.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/runtimes/grpc/_worker_runtime.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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. | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/runtimes/grpc/_worker_runtime_host.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/runtimes/grpc/_worker_runtime_host_servicer.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | """
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__)))
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/runtimes/grpc/protos/__init__.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | # -*- 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/runtimes/grpc/protos/agent_worker_pb2.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | # 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/runtimes/grpc/protos/agent_worker_pb2_grpc.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | # -*- 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/runtimes/grpc/protos/cloudevent_pb2.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/runtimes/grpc/protos/cloudevent_pb2_grpc.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/teams/__init__.py",
"file_type": ".py",
"source_type": "code"
} |
|
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/teams/magentic_one.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/teams/magentic_one_cli.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/tools/__init__.py",
"file_type": ".py",
"source_type": "code"
} |
|
Analyze this code content | from ._code_execution import CodeExecutionInput, CodeExecutionResult, PythonCodeExecutionTool
__all__ = ["CodeExecutionInput", "CodeExecutionResult", "PythonCodeExecutionTool"]
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/tools/code_execution/__init__.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/tools/code_execution/_code_execution.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | from ._langchain_adapter import LangChainToolAdapter
__all__ = ["LangChainToolAdapter"]
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/tools/langchain/__init__.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/src/autogen_ext/tools/langchain/_langchain_adapter.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/tests/test_openai_assistant_agent.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | import pytest
from autogen_ext.agents.web_surfer.playwright_controller import PlaywrightController
from playwright.async_api import async_playwright
FAKE_HTML = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fake Page</title>
</head>
<body>
<h1 id="header">Welcome to the Fake Page</h1>
<button id="click-me">Click Me</button>
<input type="text" id="input-box" />
</body>
</html>
"""
@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()
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/tests/test_playwright_controller.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/tests/test_tools.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/tests/test_websurfer_agent.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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. | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/tests/test_worker_runtime.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | # 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(
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/tests/code_executors/test_aca_dynamic_sessions.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | # 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 = {
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/tests/code_executors/test_aca_user_defined_functions.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | # 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/tests/code_executors/test_commandline_code_executor.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | # 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/tests/code_executors/test_docker_commandline_code_executor.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | # 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/tests/code_executors/test_user_defined_functions.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/tests/models/test_openai_model_client.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/tests/models/test_reply_chat_completion_client.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | # -*- 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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/tests/protos/serialization_test_pb2.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-ext/tests/protos/serialization_test_pb2_grpc.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this document content | # 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 | Document summary and key points | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/README.md",
"file_type": ".md",
"source_type": "document"
} |
Analyze this document content | # 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 | Document summary and key points | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/examples/README.md",
"file_type": ".md",
"source_type": "document"
} |
Analyze this code content | """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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/examples/example.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | """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:
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/examples/example_coder.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | """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 | Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/examples/example_file_surfer.py",
"file_type": ".py",
"source_type": "code"
} |
Analyze this code content | """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()
| Code analysis and explanation | {
"file_path": "multi_repo_data/autogen/python/packages/autogen-magentic-one/examples/example_userproxy.py",
"file_type": ".py",
"source_type": "code"
} |