mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
977c3adfb2
* python: replace pre-commit with prek, add PEP 723 script deps, clean up dev dependencies - Replace pre-commit with prek (Rust-native, faster pre-commit alternative) - Move supported hooks to repo: builtin for zero-clone speed - Add new builtin hooks: trailing-whitespace, check-merge-conflict, detect-private-key, check-added-large-files - Update all hook versions to latest (pre-commit-hooks v6, pyupgrade v3.21.2, bandit 1.9.3, uv-pre-commit 0.10.0) - Add PEP 723 inline script metadata to 34 samples with external deps - Remove autogen-agentchat/autogen-ext from dev deps (now declared per-sample) - Remove unused dev deps: pytest-env, tomli-w - Add agent-framework-core>=1.0.0b260130 lower bound to all 21 packages - Update CI workflow to use j178/prek-action - Update docs: DEV_SETUP.md, AGENTS.md, CODING_STANDARD.md, SAMPLE_GUIDELINES.md * updated lock * python: fix prek config paths for local execution and CI workflow Remove global 'files: ^python/' filter and strip python/ prefix from all path patterns in .pre-commit-config.yaml so prek finds files when run from the python/ directory. Update CI workflow to use --cd python instead of --config path. Include trailing whitespace fixes and dev dependency cleanup. * python: move helper scripts to scripts/ folder and exclude from checks * python: exclude AGENTS.md from prek markdown code lint * python: exclude AGENTS.md and azure_ai_search sample from markdown lint * fix m365 sample * python: ignore CPY rule for samples with PEP 723 headers * fix in dev_setup * python: replace aiofiles with regular open in samples * python: suppress reportUnusedImport in markdown code block checker * python: use samples pyright config for markdown code block checker Write a temp pyrightconfig.json matching pyrightconfig.samples.json rules (typeCheckingMode=off, only reportMissingImports and reportAttributeAccessIssue). Filter output to only fail on these rules since syntax-level errors (top-level await, undefined vars) are expected in README documentation snippets. * python: use markdown-code-lint with fixed globs instead of prek file list The prek-markdown-code-lint task received all changed files including non-README markdown and files with pre-existing broken imports. Replace with the standard markdown-code-lint task which uses the correct glob patterns (README.md, packages/**/README.md, samples/**/*.md). * python: exclude READMEs with pre-existing broken imports from markdown lint * python: fix broken README code snippets instead of excluding them - ag-ui: replace TextContent (removed) with content.type == 'text' - durabletask: fix import path to durabletask.worker.TaskHubGrpcWorker - orchestrations: use constructor params instead of .participants() method - observability: mark deprecated code blocks as plain text, filter reportMissingImports to agent_framework modules only - remove README excludes from markdown-code-lint task * add revision to gaia download * feat(python): parallelize checks across packages Run (package × task) cross-product in parallel using ThreadPoolExecutor and subprocesses. Key changes: - Add scripts/task_runner.py with shared parallel execution engine - Update run_tasks_in_packages_if_exists.py to accept multiple tasks - Update run_tasks_in_changed_packages.py with --files flag and parallel support - Add check-packages poe task (fmt+lint+pyright+mypy in parallel) - Add prek-markdown-code-lint and prek-samples-check with change detection - Split CI code quality workflow into parallel prek and mypy jobs - Update DEV_SETUP.md to document new parallel behavior Core package changes still trigger checks on all packages. * feat(ci): split code quality into 4 parallel jobs Split the single prek job into parallel jobs: - pre-commit-hooks: lightweight hooks (SKIP=poe-check) - package-checks: fmt/lint/pyright/mypy via check-packages - samples-markdown: samples-lint, samples-syntax, markdown-code-lint - mypy: change-detected mypy checks All 4 jobs run concurrently (×2 Python versions = 8 runners). * feat(ci): use only Python 3.10 for code quality checks * refactor(python): add future annotations and remove quoted types Add `from __future__ import annotations` to 93 package files that used quoted string annotations, then run pyupgrade --py310-plus to remove the now-unnecessary quotes. Fixes https://github.com/microsoft/agent-framework/issues/3578
172 lines
6.2 KiB
Python
172 lines
6.2 KiB
Python
# /// script
|
|
# requires-python = ">=3.10"
|
|
# dependencies = [
|
|
# "autogen-agentchat",
|
|
# "autogen-ext[openai]",
|
|
# ]
|
|
# ///
|
|
# Run with any PEP 723 compatible runner, e.g.:
|
|
# uv run samples/autogen-migration/orchestrations/04_magentic_one.py
|
|
|
|
# Copyright (c) Microsoft. All rights reserved.
|
|
"""AutoGen MagenticOneGroupChat vs Agent Framework MagenticBuilder.
|
|
|
|
Demonstrates orchestrated multi-agent workflows with a central coordinator
|
|
managing specialized agents for complex tasks.
|
|
"""
|
|
|
|
import asyncio
|
|
import json
|
|
from typing import cast
|
|
|
|
from agent_framework import (
|
|
AgentResponseUpdate,
|
|
ChatMessage,
|
|
WorkflowEvent,
|
|
)
|
|
from agent_framework.orchestrations import MagenticProgressLedger
|
|
|
|
|
|
async def run_autogen() -> None:
|
|
"""AutoGen's MagenticOneGroupChat for orchestrated collaboration."""
|
|
from autogen_agentchat.agents import AssistantAgent
|
|
from autogen_agentchat.teams import MagenticOneGroupChat
|
|
from autogen_agentchat.ui import Console
|
|
from autogen_ext.models.openai import OpenAIChatCompletionClient
|
|
|
|
client = OpenAIChatCompletionClient(model="gpt-4.1-mini")
|
|
|
|
# Create specialized agents
|
|
researcher = AssistantAgent(
|
|
name="researcher",
|
|
model_client=client,
|
|
system_message="You are a research analyst. Gather and analyze information.",
|
|
description="Research analyst for data gathering",
|
|
model_client_stream=True,
|
|
)
|
|
|
|
coder = AssistantAgent(
|
|
name="coder",
|
|
model_client=client,
|
|
system_message="You are a programmer. Write code based on requirements.",
|
|
description="Software developer for implementation",
|
|
model_client_stream=True,
|
|
)
|
|
|
|
reviewer = AssistantAgent(
|
|
name="reviewer",
|
|
model_client=client,
|
|
system_message="You are a code reviewer. Review code for quality and correctness.",
|
|
description="Code reviewer for quality assurance",
|
|
model_client_stream=True,
|
|
)
|
|
|
|
# Create MagenticOne team with coordinator
|
|
team = MagenticOneGroupChat(
|
|
participants=[researcher, coder, reviewer],
|
|
model_client=client, # Coordinator uses this client
|
|
max_turns=20,
|
|
max_stalls=3,
|
|
)
|
|
|
|
# Run complex task and display the conversation
|
|
print("[AutoGen] Magentic One conversation:")
|
|
await Console(team.run_stream(task="Research Python async patterns and write a simple example"))
|
|
|
|
|
|
async def run_agent_framework() -> None:
|
|
"""Agent Framework's MagenticBuilder for orchestrated collaboration."""
|
|
from agent_framework.openai import OpenAIChatClient
|
|
from agent_framework.orchestrations import MagenticBuilder
|
|
|
|
client = OpenAIChatClient(model_id="gpt-4.1-mini")
|
|
|
|
# Create specialized agents
|
|
researcher = client.as_agent(
|
|
name="researcher",
|
|
instructions="You are a research analyst. Gather and analyze information.",
|
|
description="Research analyst for data gathering",
|
|
)
|
|
|
|
coder = client.as_agent(
|
|
name="coder",
|
|
instructions="You are a programmer. Write code based on requirements.",
|
|
description="Software developer for implementation",
|
|
)
|
|
|
|
reviewer = client.as_agent(
|
|
name="reviewer",
|
|
instructions="You are a code reviewer. Review code for quality and correctness.",
|
|
description="Code reviewer for quality assurance",
|
|
)
|
|
|
|
# Create Magentic workflow
|
|
workflow = MagenticBuilder(
|
|
participants=[researcher, coder, reviewer],
|
|
manager_agent=client.as_agent(
|
|
name="magentic_manager",
|
|
instructions="You coordinate a team to complete complex tasks efficiently.",
|
|
description="Orchestrator for team coordination",
|
|
),
|
|
max_round_count=20,
|
|
max_stall_count=3,
|
|
max_reset_count=1,
|
|
).build()
|
|
|
|
# Run complex task
|
|
last_message_id: str | None = None
|
|
output_event: WorkflowEvent | None = None
|
|
print("[Agent Framework] Magentic conversation:")
|
|
async for event in workflow.run("Research Python async patterns and write a simple example", stream=True):
|
|
if event.type == "output" and isinstance(event.data, AgentResponseUpdate):
|
|
message_id = event.data.message_id
|
|
if message_id != last_message_id:
|
|
if last_message_id is not None:
|
|
print("\n")
|
|
print(f"- {event.executor_id}:", end=" ", flush=True)
|
|
last_message_id = message_id
|
|
print(event.data, end="", flush=True)
|
|
|
|
elif event.type == "magentic_orchestrator":
|
|
print(f"\n[Magentic Orchestrator Event] Type: {event.data.event_type.name}")
|
|
if isinstance(event.data.content, ChatMessage):
|
|
print(f"Please review the plan:\n{event.data.content.text}")
|
|
elif isinstance(event.data.content, MagenticProgressLedger):
|
|
print(f"Please review progress ledger:\n{json.dumps(event.data.content.to_dict(), indent=2)}")
|
|
else:
|
|
print(f"Unknown data type in MagenticOrchestratorEvent: {type(event.data.content)}")
|
|
|
|
# Block to allow user to read the plan/progress before continuing
|
|
# Note: this is for demonstration only and is not the recommended way to handle human interaction.
|
|
# Please refer to `with_plan_review` for proper human interaction during planning phases.
|
|
await asyncio.get_event_loop().run_in_executor(None, input, "Press Enter to continue...")
|
|
|
|
elif event.type == "output":
|
|
output_event = event
|
|
|
|
if not output_event:
|
|
raise RuntimeError("Workflow did not produce a final output event.")
|
|
print("\n\nWorkflow completed!")
|
|
print("Final Output:")
|
|
# The output of the Magentic workflow is a list of ChatMessages with only one final message
|
|
# generated by the orchestrator.
|
|
output_messages = cast(list[ChatMessage], output_event.data)
|
|
if output_messages:
|
|
output = output_messages[-1].text
|
|
print(output)
|
|
|
|
|
|
async def main() -> None:
|
|
print("=" * 60)
|
|
print("Magentic One Orchestration Comparison")
|
|
print("=" * 60)
|
|
print("AutoGen: MagenticOneGroupChat")
|
|
print("Agent Framework: MagenticBuilder\n")
|
|
await run_autogen()
|
|
print()
|
|
await run_agent_framework()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
asyncio.run(main())
|