Skip to content

Commit

Permalink
Merge branch 'main' into u/#4354
Browse files Browse the repository at this point in the history
  • Loading branch information
rysweet authored Dec 3, 2024
2 parents bfa5c1b + c062c51 commit 0e05a41
Show file tree
Hide file tree
Showing 12 changed files with 35 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ async def Console(
f"Duration: {duration:.2f} seconds\n"
)
sys.stdout.write(output)
sys.stdout.flush()
# mypy ignore
last_processed = message # type: ignore

Expand All @@ -71,6 +72,7 @@ async def Console(
total_usage.completion_tokens += message.chat_message.models_usage.completion_tokens
total_usage.prompt_tokens += message.chat_message.models_usage.prompt_tokens
sys.stdout.write(output)
sys.stdout.flush()

# Print summary.
if message.inner_messages is not None:
Expand All @@ -85,6 +87,7 @@ async def Console(
f"Duration: {duration:.2f} seconds\n"
)
sys.stdout.write(output)
sys.stdout.flush()
# mypy ignore
last_processed = message # type: ignore

Expand All @@ -97,6 +100,7 @@ async def Console(
total_usage.completion_tokens += message.models_usage.completion_tokens
total_usage.prompt_tokens += message.models_usage.prompt_tokens
sys.stdout.write(output)
sys.stdout.flush()

if last_processed is None:
raise ValueError("No TaskResult or Response was processed.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def prepare_writing(self, docnames: AbstractSet[str]) -> None:

def write_doc(self, docname: str, doctree: nodes.Node) -> None:
path_prefix: str = self.app.config.code_lint_path_prefix
supported_languages = set(["python"])
supported_languages = set(["python", "default"])

if not docname.startswith(path_prefix):
return
Expand Down
1 change: 1 addition & 0 deletions python/packages/autogen-core/docs/src/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@
}

autodoc_pydantic_model_show_config_summary = False
python_use_unqualified_type_names = True

intersphinx_mapping = {"python": ("https://docs.python.org/3", None)}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from ._agent_id import AgentId
from ._agent_instantiation import AgentInstantiationContext
from ._agent_metadata import AgentMetadata
from ._agent_props import AgentChildren
from ._agent_proxy import AgentProxy
from ._agent_runtime import AgentRuntime
from ._agent_type import AgentType
Expand Down Expand Up @@ -34,7 +33,6 @@
"AgentRuntime",
"BaseAgent",
"CancellationToken",
"AgentChildren",
"AgentInstantiationContext",
"TopicId",
"Subscription",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,24 @@ def __init__(self) -> None:
"AgentInstantiationContext cannot be instantiated. It is a static class that provides context management for agent instantiation."
)

AGENT_INSTANTIATION_CONTEXT_VAR: ClassVar[ContextVar[tuple[AgentRuntime, AgentId]]] = ContextVar(
"AGENT_INSTANTIATION_CONTEXT_VAR"
_AGENT_INSTANTIATION_CONTEXT_VAR: ClassVar[ContextVar[tuple[AgentRuntime, AgentId]]] = ContextVar(
"_AGENT_INSTANTIATION_CONTEXT_VAR"
)

@classmethod
@contextmanager
def populate_context(cls, ctx: tuple[AgentRuntime, AgentId]) -> Generator[None, Any, None]:
token = AgentInstantiationContext.AGENT_INSTANTIATION_CONTEXT_VAR.set(ctx)
""":meta private:"""
token = AgentInstantiationContext._AGENT_INSTANTIATION_CONTEXT_VAR.set(ctx)
try:
yield
finally:
AgentInstantiationContext.AGENT_INSTANTIATION_CONTEXT_VAR.reset(token)
AgentInstantiationContext._AGENT_INSTANTIATION_CONTEXT_VAR.reset(token)

@classmethod
def current_runtime(cls) -> AgentRuntime:
try:
return cls.AGENT_INSTANTIATION_CONTEXT_VAR.get()[0]
return cls._AGENT_INSTANTIATION_CONTEXT_VAR.get()[0]
except LookupError as e:
raise RuntimeError(
"AgentInstantiationContext.runtime() must be called within an instantiation context such as when the AgentRuntime is instantiating an agent. Mostly likely this was caused by directly instantiating an agent instead of using the AgentRuntime to do so."
Expand All @@ -37,7 +38,7 @@ def current_runtime(cls) -> AgentRuntime:
@classmethod
def current_agent_id(cls) -> AgentId:
try:
return cls.AGENT_INSTANTIATION_CONTEXT_VAR.get()[1]
return cls._AGENT_INSTANTIATION_CONTEXT_VAR.get()[1]
except LookupError as e:
raise RuntimeError(
"AgentInstantiationContext.agent_id() must be called within an instantiation context such as when the AgentRuntime is instantiating an agent. Mostly likely this was caused by directly instantiating an agent instead of using the AgentRuntime to do so."
Expand Down
11 changes: 0 additions & 11 deletions python/packages/autogen-core/src/autogen_core/base/_agent_props.py

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,9 @@ async def register(
) -> AgentType:
"""Register an agent factory with the runtime associated with a specific type. The type must be unique.
.. deprecated:: 0.4.0.dev1
Use a specific agent's `register` method directly instead of this method. For example: :meth:`BaseAgent.register`
Args:
type (str): The type of agent this factory creates. It is not the same as agent class name. The `type` parameter is used to differentiate between different factory functions rather than agent classes.
agent_factory (Callable[[], T]): The factory that creates the agent, where T is a concrete Agent type. Inside the factory, use `autogen_core.base.AgentInstantiationContext` to access variables like the current runtime and agent ID.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@

# Decorator for adding an unbound subscription to an agent
def subscription_factory(subscription: UnboundSubscription) -> Callable[[Type[BaseAgentType]], Type[BaseAgentType]]:
""":meta private:"""

def decorator(cls: Type[BaseAgentType]) -> Type[BaseAgentType]:
cls.internal_unbound_subscriptions_list.append(subscription)
return cls
Expand Down Expand Up @@ -56,7 +58,9 @@ def decorator(cls: Type[BaseAgentType]) -> Type[BaseAgentType]:

class BaseAgent(ABC, Agent):
internal_unbound_subscriptions_list: ClassVar[List[UnboundSubscription]] = []
""":meta private:"""
internal_extra_handles_types: ClassVar[List[Tuple[Type[Any], List[MessageSerializer[Any]]]]] = []
""":meta private:"""

def __init_subclass__(cls, **kwargs: Any) -> None:
super().__init_subclass__(**kwargs)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,21 @@ def __init__(self) -> None:
"MessageHandlerContext cannot be instantiated. It is a static class that provides context management for agent instantiation."
)

MESSAGE_HANDLER_CONTEXT: ClassVar[ContextVar[AgentId]] = ContextVar("MESSAGE_HANDLER_CONTEXT")
_MESSAGE_HANDLER_CONTEXT: ClassVar[ContextVar[AgentId]] = ContextVar("_MESSAGE_HANDLER_CONTEXT")

@classmethod
@contextmanager
def populate_context(cls, ctx: AgentId) -> Generator[None, Any, None]:
token = MessageHandlerContext.MESSAGE_HANDLER_CONTEXT.set(ctx)
""":meta private:"""
token = MessageHandlerContext._MESSAGE_HANDLER_CONTEXT.set(ctx)
try:
yield
finally:
MessageHandlerContext.MESSAGE_HANDLER_CONTEXT.reset(token)
MessageHandlerContext._MESSAGE_HANDLER_CONTEXT.reset(token)

@classmethod
def agent_id(cls) -> AgentId:
try:
return cls.MESSAGE_HANDLER_CONTEXT.get()
return cls._MESSAGE_HANDLER_CONTEXT.get()
except LookupError as e:
raise RuntimeError("MessageHandlerContext.agent_id() must be called within a message handler.") from e
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,8 @@ def _type_name(cls: type[Any] | Any) -> str:


def try_get_known_serializers_for_type(cls: type[Any]) -> list[MessageSerializer[Any]]:
""":meta private:"""

serializers: List[MessageSerializer[Any]] = []
if issubclass(cls, BaseModel):
serializers.append(PydanticJsonMessageSerializer(cls))
Expand All @@ -211,6 +213,8 @@ def try_get_known_serializers_for_type(cls: type[Any]) -> list[MessageSerializer


class SerializationRegistry:
""":meta private:"""

def __init__(self) -> None:
# type_name, data_content_type -> serializer
self._serializers: dict[tuple[str, str], MessageSerializer[Any]] = {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,22 @@ def __init__(self) -> None:
"SubscriptionInstantiationContext cannot be instantiated. It is a static class that provides context management for subscription instantiation."
)

SUBSCRIPTION_CONTEXT_VAR: ClassVar[ContextVar[AgentType]] = ContextVar("SUBSCRIPTION_CONTEXT_VAR")
_SUBSCRIPTION_CONTEXT_VAR: ClassVar[ContextVar[AgentType]] = ContextVar("_SUBSCRIPTION_CONTEXT_VAR")

@classmethod
@contextmanager
def populate_context(cls, ctx: AgentType) -> Generator[None, Any, None]:
token = SubscriptionInstantiationContext.SUBSCRIPTION_CONTEXT_VAR.set(ctx)
""":meta private:"""
token = SubscriptionInstantiationContext._SUBSCRIPTION_CONTEXT_VAR.set(ctx)
try:
yield
finally:
SubscriptionInstantiationContext.SUBSCRIPTION_CONTEXT_VAR.reset(token)
SubscriptionInstantiationContext._SUBSCRIPTION_CONTEXT_VAR.reset(token)

@classmethod
def agent_type(cls) -> AgentType:
try:
return cls.SUBSCRIPTION_CONTEXT_VAR.get()
return cls._SUBSCRIPTION_CONTEXT_VAR.get()
except LookupError as e:
raise RuntimeError(
"SubscriptionInstantiationContext.runtime() must be called within an instantiation context such as when the AgentRuntime is instantiating an agent. Mostly likely this was caused by directly instantiating an agent instead of using the AgentRuntime to do so."
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ def wrapper(func: Callable[P, T]) -> FunctionWithRequirements[T, P]:
def build_python_functions_file(
funcs: Sequence[Union[FunctionWithRequirements[Any, P], Callable[..., Any], FunctionWithRequirementsStr]],
) -> str:
""":meta private:"""
# First collect all global imports
global_imports: Set[Import] = set()
for func in funcs:
Expand Down

0 comments on commit 0e05a41

Please sign in to comment.