Skip to content

Commit

Permalink
rebase python dir to main
Browse files Browse the repository at this point in the history
  • Loading branch information
rysweet committed Nov 27, 2024
1 parent bb547a6 commit 7144d4f
Show file tree
Hide file tree
Showing 99 changed files with 3,687 additions and 5,079 deletions.
13 changes: 4 additions & 9 deletions python/README.md
Original file line number Diff line number Diff line change
@@ -1,26 +1,21 @@
# AutoGen Python packages

See [`autogen-core`](./packages/autogen-core/) package for main functionality.
[![0.4 Docs](https://img.shields.io/badge/Docs-0.4-blue)](https://microsoft.github.io/autogen/dev/)
[![PyPi autogen-core](https://img.shields.io/badge/PyPi-autogen--core-blue?logo=pypi)](https://pypi.org/project/autogen-core/0.4.0.dev7/) [![PyPi autogen-agentchat](https://img.shields.io/badge/PyPi-autogen--agentchat-blue?logo=pypi)](https://pypi.org/project/autogen-agentchat/0.4.0.dev7/) [![PyPi autogen-ext](https://img.shields.io/badge/PyPi-autogen--ext-blue?logo=pypi)](https://pypi.org/project/autogen-ext/0.4.0.dev7/)


This directory works as a single `uv` workspace containing all project packages. See [`packages`](./packages/) to discover all project packages.

## Development

**TL;DR**, run all checks with:

macOS & Linux:
```sh
uv sync --all-extras
source .venv/bin/activate
poe check
```

Windows (pwsh):
```sh
uv sync --all-extras
./.venv/Scripts/activate.ps1
poe check
```

### Setup
`uv` is a package manager that assists in creating the necessary environment and installing packages to run AutoGen.
- [Install `uv`](https://docs.astral.sh/uv/getting-started/installation/).
Expand Down
1 change: 1 addition & 0 deletions python/packages/autogen-agentchat/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ include = ["src/**", "tests/*.py"]
[tool.pyright]
extends = "../../pyproject.toml"
include = ["src", "tests"]
reportDeprecated = true

[tool.pytest.ini_options]
minversion = "6.0"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
MessageContext,
)
from autogen_core.components import ClosureAgent, TypeSubscription
from autogen_core.components._closure_agent import ClosureContext

from ... import EVENT_LOGGER_NAME
from ...base import ChatAgent, TaskResult, Team, TerminationCondition
Expand Down Expand Up @@ -139,8 +140,7 @@ async def _init(self, runtime: AgentRuntime) -> None:
)

async def collect_output_messages(
_runtime: AgentRuntime,
id: AgentId,
_runtime: ClosureContext,
message: GroupChatStart | GroupChatMessage | GroupChatTermination,
ctx: MessageContext,
) -> None:
Expand All @@ -150,7 +150,7 @@ async def collect_output_messages(
return
await self._output_message_queue.put(message.message)

await ClosureAgent.register(
await ClosureAgent.register_closure(
runtime,
type=self._collector_agent_type,
closure=collect_output_messages,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ def _create_group_chat_manager_factory(
return lambda: MagenticOneOrchestrator(
group_topic_type,
output_topic_type,
self._team_id,
participant_topic_types,
participant_descriptions,
max_turns,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import json
from typing import Any, List

from autogen_core.base import MessageContext
from autogen_core.base import MessageContext, AgentId
from autogen_core.components import DefaultTopicId, Image, event, rpc
from autogen_core.components.models import (
AssistantMessage,
Expand Down Expand Up @@ -42,6 +42,7 @@ def __init__(
self,
group_topic_type: str,
output_topic_type: str,
team_id: str,
participant_topic_types: List[str],
participant_descriptions: List[str],
max_turns: int | None,
Expand All @@ -51,6 +52,7 @@ def __init__(
super().__init__(description="Group chat manager")
self._group_topic_type = group_topic_type
self._output_topic_type = output_topic_type
self._team_id = team_id
if len(participant_topic_types) != len(participant_descriptions):
raise ValueError("The number of participant topic types, agent types, and descriptions must be the same.")
if len(set(participant_topic_types)) != len(participant_topic_types):
Expand Down Expand Up @@ -164,10 +166,13 @@ async def on_unhandled_message(self, message: Any, ctx: MessageContext) -> None:

async def _reenter_inner_loop(self) -> None:
# Reset the agents
await self.publish_message(
GroupChatReset(),
topic_id=DefaultTopicId(type=self._group_topic_type),
)
for participant_topic_type in self._participant_topic_types:
await self._runtime.send_message(
GroupChatReset(),
recipient=AgentId(type=participant_topic_type, key=self._team_id),
)
# Reset the group chat manager
await self.reset()
self._message_thread.clear()

# Prepare the ledger
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,16 @@
},
{
"cell_type": "code",
"execution_count": 1,
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import asyncio\n",
"from dataclasses import dataclass\n",
"\n",
"from autogen_core.application import SingleThreadedAgentRuntime\n",
"from autogen_core.base import AgentId, AgentRuntime, MessageContext\n",
"from autogen_core.components import ClosureAgent, DefaultSubscription, DefaultTopicId"
"from autogen_core.base import MessageContext\n",
"from autogen_core.components import ClosureAgent, ClosureContext, DefaultSubscription, DefaultTopicId"
]
},
{
Expand Down Expand Up @@ -77,11 +77,11 @@
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"async def output_result(_runtime: AgentRuntime, id: AgentId, message: FinalResult, ctx: MessageContext) -> None:\n",
"async def output_result(_agent: ClosureContext, message: FinalResult, ctx: MessageContext) -> None:\n",
" await queue.put(message)"
]
},
Expand All @@ -94,7 +94,7 @@
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": null,
"metadata": {},
"outputs": [
{
Expand All @@ -110,7 +110,9 @@
],
"source": [
"runtime = SingleThreadedAgentRuntime()\n",
"await ClosureAgent.register(runtime, \"output_result\", output_result, subscriptions=lambda: [DefaultSubscription()])"
"await ClosureAgent.register_closure(\n",
" runtime, \"output_result\", output_result, subscriptions=lambda: [DefaultSubscription()]\n",
")"
]
},
{
Expand Down
9 changes: 5 additions & 4 deletions python/packages/autogen-core/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ dependencies = [
"opentelemetry-api~=1.27.0",
"asyncio_atexit",
"jsonref~=1.1.0",
"grpcio~=1.62.0", # TODO: update this once we have a stable version.
]

[project.optional-dependencies]
Expand Down Expand Up @@ -81,7 +82,7 @@ dev-dependencies = [

[tool.ruff]
extend = "../../pyproject.toml"
exclude = ["build", "dist", "src/autogen_core/application/protos"]
exclude = ["build", "dist", "src/autogen_core/application/protos", "tests/protos"]
include = ["src/**", "samples/*.py", "docs/**/*.ipynb", "tests/**"]

[tool.ruff.lint.per-file-ignores]
Expand All @@ -91,8 +92,8 @@ include = ["src/**", "samples/*.py", "docs/**/*.ipynb", "tests/**"]
[tool.pyright]
extends = "../../pyproject.toml"
include = ["src", "tests", "samples"]
exclude = ["src/autogen_core/application/protos"]
reportDeprecated = false
exclude = ["src/autogen_core/application/protos", "tests/protos"]
reportDeprecated = true

[tool.pytest.ini_options]
minversion = "6.0"
Expand All @@ -111,7 +112,7 @@ include = "../../shared_tasks.toml"
test = "pytest -n auto"
mypy.default_item_type = "cmd"
mypy.sequence = [
"mypy --config-file ../../pyproject.toml --exclude src/autogen_core/application/protos src tests",
"mypy --config-file ../../pyproject.toml --exclude src/autogen_core/application/protos --exclude tests/protos src tests",
"nbqa mypy docs/src --config-file ../../pyproject.toml",
]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@
WorkerAgentMessage,
)
from autogen_core.application import WorkerAgentRuntime
from autogen_core.base import AgentId, AgentRuntime, MessageContext
from autogen_core.components import ClosureAgent, DefaultSubscription, DefaultTopicId
from autogen_core.base import MessageContext
from autogen_core.components import ClosureAgent, ClosureContext, DefaultSubscription, DefaultTopicId


class MockIntentClassifier(IntentClassifierBase):
Expand All @@ -60,20 +60,20 @@ async def get_agent(self, intent: str) -> str:


async def output_result(
_runtime: AgentRuntime, id: AgentId, message: WorkerAgentMessage | FinalResult, ctx: MessageContext
closure_ctx: ClosureContext, message: WorkerAgentMessage | FinalResult, ctx: MessageContext
) -> None:
if isinstance(message, WorkerAgentMessage):
print(f"{message.source} Agent: {message.content}")
new_message = input("User response: ")
await _runtime.publish_message(
await closure_ctx.publish_message(
UserProxyMessage(content=new_message, source="user"),
topic_id=DefaultTopicId(type=message.source, source="user"),
)
else:
print(f"{message.source} Agent: {message.content}")
print("Conversation ended")
new_message = input("Enter a new conversation start: ")
await _runtime.publish_message(
await closure_ctx.publish_message(
UserProxyMessage(content=new_message, source="user"), topic_id=DefaultTopicId(type="default", source="user")
)

Expand All @@ -95,7 +95,7 @@ async def run_workers():
await agent_runtime.add_subscription(DefaultSubscription(topic_type="user_proxy", agent_type="user_proxy"))

# A closure agent surfaces the final result to external systems (e.g. an API) so that the system can interact with the user
await ClosureAgent.register(
await ClosureAgent.register_closure(
agent_runtime,
"closure_agent",
output_result,
Expand Down
20 changes: 12 additions & 8 deletions python/packages/autogen-core/samples/slow_human_in_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,13 @@
from autogen_core.application import SingleThreadedAgentRuntime
from autogen_core.base import AgentId, CancellationToken, MessageContext
from autogen_core.base.intervention import DefaultInterventionHandler
from autogen_core.components import DefaultSubscription, DefaultTopicId, FunctionCall, RoutedAgent, message_handler
from autogen_core.components import (
DefaultTopicId,
FunctionCall,
RoutedAgent,
message_handler,
type_subscription,
)
from autogen_core.components.model_context import BufferedChatCompletionContext
from autogen_core.components.models import (
AssistantMessage,
Expand Down Expand Up @@ -81,6 +87,7 @@ def save_content(self, content: Mapping[str, Any]) -> None:
state_persister = MockPersistence()


@type_subscription("scheduling_assistant_conversation")
class SlowUserProxyAgent(RoutedAgent):
def __init__(
self,
Expand Down Expand Up @@ -132,6 +139,7 @@ async def run(self, args: ScheduleMeetingInput, cancellation_token: Cancellation
return ScheduleMeetingOutput()


@type_subscription("scheduling_assistant_conversation")
class SchedulingAssistantAgent(RoutedAgent):
def __init__(
self,
Expand Down Expand Up @@ -256,24 +264,20 @@ async def main(latest_user_input: Optional[str] = None) -> None | str:
needs_user_input_handler = NeedsUserInputHandler()
runtime = SingleThreadedAgentRuntime(intervention_handlers=[needs_user_input_handler, termination_handler])

await runtime.register(
"User",
lambda: SlowUserProxyAgent("User", "I am a user"),
subscriptions=lambda: [DefaultSubscription("scheduling_assistant_conversation")],
)
await SlowUserProxyAgent.register(runtime, "User", lambda: SlowUserProxyAgent("User", "I am a user"))

initial_schedule_assistant_message = AssistantTextMessage(
content="Hi! How can I help you? I can help schedule meetings", source="User"
)
await runtime.register(
await SchedulingAssistantAgent.register(
runtime,
"SchedulingAssistant",
lambda: SchedulingAssistantAgent(
"SchedulingAssistant",
description="AI that helps you schedule meetings",
model_client=get_chat_completion_client_from_envs(model="gpt-4o-mini"),
initial_message=initial_schedule_assistant_message,
),
subscriptions=lambda: [DefaultSubscription("scheduling_assistant_conversation")],
)

if latest_user_input is not None:
Expand Down
39 changes: 0 additions & 39 deletions python/packages/autogen-core/samples/xlang/user_input.py

This file was deleted.

Loading

0 comments on commit 7144d4f

Please sign in to comment.