mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
Python: AutoGen migration samples (#1738)
* add autogen migration samples * fix typo * remove comment * fix typo * fix lab pyright * fix for HuggingFace change
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
"""Basic AutoGen AssistantAgent vs Agent Framework ChatAgent.
|
||||
|
||||
Both samples expect OpenAI-compatible environment variables (OPENAI_API_KEY or
|
||||
Azure OpenAI configuration). Update the prompts or client wiring to match your
|
||||
model of choice before running.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
||||
|
||||
async def run_autogen() -> None:
|
||||
"""Call AutoGen's AssistantAgent for a simple question."""
|
||||
from autogen_agentchat.agents import AssistantAgent
|
||||
from autogen_ext.models.openai import OpenAIChatCompletionClient
|
||||
|
||||
# AutoGen agent with OpenAI model client
|
||||
client = OpenAIChatCompletionClient(model="gpt-4.1-mini")
|
||||
agent = AssistantAgent(
|
||||
name="assistant",
|
||||
model_client=client,
|
||||
system_message="You are a helpful assistant. Answer in one sentence.",
|
||||
)
|
||||
|
||||
# Run the agent (AutoGen maintains conversation state internally)
|
||||
result = await agent.run(task="What is the capital of France?")
|
||||
print("[AutoGen]", result.messages[-1].to_text())
|
||||
|
||||
|
||||
async def run_agent_framework() -> None:
|
||||
"""Call Agent Framework's ChatAgent created from OpenAIChatClient."""
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
|
||||
# AF constructs a lightweight ChatAgent backed by OpenAIChatClient
|
||||
client = OpenAIChatClient(model_id="gpt-4.1-mini")
|
||||
agent = client.create_agent(
|
||||
name="assistant",
|
||||
instructions="You are a helpful assistant. Answer in one sentence.",
|
||||
)
|
||||
|
||||
# Run the agent (AF agents are stateless by default)
|
||||
result = await agent.run("What is the capital of France?")
|
||||
print("[Agent Framework]", result.text)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=" * 60)
|
||||
print("Basic Assistant Agent Comparison")
|
||||
print("=" * 60)
|
||||
await run_autogen()
|
||||
print()
|
||||
await run_agent_framework()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,89 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
"""AutoGen AssistantAgent vs Agent Framework ChatAgent with function tools.
|
||||
|
||||
Demonstrates how to create and attach tools to agents in both frameworks.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
||||
|
||||
async def run_autogen() -> None:
|
||||
"""AutoGen agent with a FunctionTool."""
|
||||
from autogen_agentchat.agents import AssistantAgent
|
||||
from autogen_core.tools import FunctionTool
|
||||
from autogen_ext.models.openai import OpenAIChatCompletionClient
|
||||
|
||||
# Define a simple tool function
|
||||
def get_weather(location: str) -> str:
|
||||
"""Get the weather for a location.
|
||||
|
||||
Args:
|
||||
location: The city name or location.
|
||||
|
||||
Returns:
|
||||
A weather description.
|
||||
"""
|
||||
return f"The weather in {location} is sunny and 72°F."
|
||||
|
||||
# Wrap function in FunctionTool
|
||||
weather_tool = FunctionTool(
|
||||
func=get_weather,
|
||||
description="Get weather information for a location",
|
||||
)
|
||||
|
||||
# Create agent with tool
|
||||
client = OpenAIChatCompletionClient(model="gpt-4.1-mini")
|
||||
agent = AssistantAgent(
|
||||
name="assistant",
|
||||
model_client=client,
|
||||
tools=[weather_tool],
|
||||
system_message="You are a helpful assistant. Use available tools to answer questions.",
|
||||
)
|
||||
|
||||
# Run with tool usage
|
||||
result = await agent.run(task="What's the weather in Seattle?")
|
||||
print("[AutoGen]", result.messages[-1].to_text())
|
||||
|
||||
|
||||
async def run_agent_framework() -> None:
|
||||
"""Agent Framework agent with @ai_function decorator."""
|
||||
from agent_framework import ai_function
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
|
||||
# Define tool with @ai_function decorator (automatic schema inference)
|
||||
@ai_function
|
||||
def get_weather(location: str) -> str:
|
||||
"""Get the weather for a location.
|
||||
|
||||
Args:
|
||||
location: The city name or location.
|
||||
|
||||
Returns:
|
||||
A weather description.
|
||||
"""
|
||||
return f"The weather in {location} is sunny and 72°F."
|
||||
|
||||
# Create agent with tool
|
||||
client = OpenAIChatClient(model_id="gpt-4.1-mini")
|
||||
agent = client.create_agent(
|
||||
name="assistant",
|
||||
instructions="You are a helpful assistant. Use available tools to answer questions.",
|
||||
tools=[get_weather],
|
||||
)
|
||||
|
||||
# Run with tool usage
|
||||
result = await agent.run("What's the weather in Seattle?")
|
||||
print("[Agent Framework]", result.text)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=" * 60)
|
||||
print("Assistant Agent with Tools Comparison")
|
||||
print("=" * 60)
|
||||
await run_autogen()
|
||||
print()
|
||||
await run_agent_framework()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,79 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
"""AutoGen vs Agent Framework: Thread management and streaming responses.
|
||||
|
||||
Demonstrates conversation state management and streaming in both frameworks.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
||||
|
||||
async def run_autogen() -> None:
|
||||
"""AutoGen agent with conversation history and streaming."""
|
||||
from autogen_agentchat.agents import AssistantAgent
|
||||
from autogen_agentchat.ui import Console
|
||||
from autogen_ext.models.openai import OpenAIChatCompletionClient
|
||||
|
||||
client = OpenAIChatCompletionClient(model="gpt-4.1-mini")
|
||||
agent = AssistantAgent(
|
||||
name="assistant",
|
||||
model_client=client,
|
||||
system_message="You are a helpful math tutor.",
|
||||
model_client_stream=True,
|
||||
)
|
||||
|
||||
print("[AutoGen] Conversation with history:")
|
||||
# First turn - AutoGen maintains state internally with Console for streaming
|
||||
result = await agent.run(task="What is 15 + 27?")
|
||||
print(f" Q1: {result.messages[-1].to_text()}")
|
||||
|
||||
# Second turn - agent remembers context
|
||||
result = await agent.run(task="What about that number times 2?")
|
||||
print(f" Q2: {result.messages[-1].to_text()}")
|
||||
|
||||
print("\n[AutoGen] Streaming response:")
|
||||
# Stream response with Console for token streaming
|
||||
await Console(agent.run_stream(task="Count from 1 to 5"))
|
||||
|
||||
|
||||
async def run_agent_framework() -> None:
|
||||
"""Agent Framework agent with explicit thread and streaming."""
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
|
||||
client = OpenAIChatClient(model_id="gpt-4.1-mini")
|
||||
agent = client.create_agent(
|
||||
name="assistant",
|
||||
instructions="You are a helpful math tutor.",
|
||||
)
|
||||
|
||||
print("[Agent Framework] Conversation with thread:")
|
||||
# Create a thread to maintain state
|
||||
thread = agent.get_new_thread()
|
||||
|
||||
# First turn - pass thread to maintain history
|
||||
result1 = await agent.run("What is 15 + 27?", thread=thread)
|
||||
print(f" Q1: {result1.text}")
|
||||
|
||||
# Second turn - agent remembers context via thread
|
||||
result2 = await agent.run("What about that number times 2?", thread=thread)
|
||||
print(f" Q2: {result2.text}")
|
||||
|
||||
print("\n[Agent Framework] Streaming response:")
|
||||
# Stream response
|
||||
print(" ", end="")
|
||||
async for chunk in agent.run_stream("Count from 1 to 5"):
|
||||
if chunk.text:
|
||||
print(chunk.text, end="", flush=True)
|
||||
print()
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=" * 60)
|
||||
print("Thread Management and Streaming Comparison")
|
||||
print("=" * 60)
|
||||
await run_autogen()
|
||||
print()
|
||||
await run_agent_framework()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,130 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
"""AutoGen vs Agent Framework: Agent-as-a-Tool pattern.
|
||||
|
||||
Demonstrates hierarchical agent architectures where one agent delegates
|
||||
work to specialized sub-agents wrapped as tools.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
||||
|
||||
async def run_autogen() -> None:
|
||||
"""AutoGen's AgentTool for hierarchical agents with streaming."""
|
||||
from autogen_agentchat.agents import AssistantAgent
|
||||
from autogen_agentchat.tools import AgentTool
|
||||
from autogen_agentchat.ui import Console
|
||||
from autogen_ext.models.openai import OpenAIChatCompletionClient
|
||||
|
||||
# Create a specialized writer agent
|
||||
writer_client = OpenAIChatCompletionClient(model="gpt-4.1-mini")
|
||||
writer = AssistantAgent(
|
||||
name="writer",
|
||||
model_client=writer_client,
|
||||
system_message="You are a creative writer. Write short, engaging content.",
|
||||
model_client_stream=True,
|
||||
)
|
||||
|
||||
# Wrap writer agent as a tool (description is taken from agent.description)
|
||||
writer_tool = AgentTool(agent=writer)
|
||||
|
||||
# Create coordinator agent with writer as a tool
|
||||
# IMPORTANT: Disable parallel_tool_calls when using AgentTool
|
||||
coordinator_client = OpenAIChatCompletionClient(
|
||||
model="gpt-4.1-mini",
|
||||
parallel_tool_calls=False,
|
||||
)
|
||||
coordinator = AssistantAgent(
|
||||
name="coordinator",
|
||||
model_client=coordinator_client,
|
||||
tools=[writer_tool],
|
||||
system_message="You coordinate with specialized agents. Delegate writing tasks to the writer agent.",
|
||||
model_client_stream=True,
|
||||
)
|
||||
|
||||
# Run coordinator with streaming - it will delegate to writer
|
||||
print("[AutoGen]")
|
||||
await Console(coordinator.run_stream(task="Create a tagline for a coffee shop"))
|
||||
|
||||
|
||||
async def run_agent_framework() -> None:
|
||||
"""Agent Framework's as_tool() for hierarchical agents with streaming."""
|
||||
from agent_framework import FunctionCallContent, FunctionResultContent
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
|
||||
client = OpenAIChatClient(model_id="gpt-4.1-mini")
|
||||
|
||||
# Create specialized writer agent
|
||||
writer = client.create_agent(
|
||||
name="writer",
|
||||
instructions="You are a creative writer. Write short, engaging content.",
|
||||
)
|
||||
|
||||
# Convert writer to a tool using as_tool()
|
||||
writer_tool = writer.as_tool(
|
||||
name="creative_writer",
|
||||
description="Generate creative content",
|
||||
arg_name="request",
|
||||
arg_description="What to write",
|
||||
)
|
||||
|
||||
# Create coordinator agent with writer tool
|
||||
coordinator = client.create_agent(
|
||||
name="coordinator",
|
||||
instructions="You coordinate with specialized agents. Delegate writing tasks to the writer agent.",
|
||||
tools=[writer_tool],
|
||||
)
|
||||
|
||||
# Run coordinator with streaming - it will delegate to writer
|
||||
print("[Agent Framework]")
|
||||
|
||||
# Track accumulated function calls (they stream in incrementally)
|
||||
accumulated_calls: dict[str, FunctionCallContent] = {}
|
||||
|
||||
async for chunk in coordinator.run_stream("Create a tagline for a coffee shop"):
|
||||
# Stream text tokens
|
||||
if chunk.text:
|
||||
print(chunk.text, end="", flush=True)
|
||||
|
||||
# Process streaming function calls and results
|
||||
if chunk.contents:
|
||||
for content in chunk.contents:
|
||||
if isinstance(content, FunctionCallContent):
|
||||
# Accumulate function call content as it streams in
|
||||
call_id = content.call_id
|
||||
if call_id in accumulated_calls:
|
||||
# Add to existing call (arguments stream in gradually)
|
||||
accumulated_calls[call_id] = accumulated_calls[call_id] + content
|
||||
else:
|
||||
# First chunk of this function call
|
||||
accumulated_calls[call_id] = content
|
||||
print("\n[Function Call - streaming]", flush=True)
|
||||
print(f" Call ID: {call_id}", flush=True)
|
||||
print(f" Name: {content.name}", flush=True)
|
||||
|
||||
# Show accumulated arguments so far
|
||||
current_args = accumulated_calls[call_id].arguments
|
||||
print(f" Arguments: {current_args}", flush=True)
|
||||
|
||||
elif isinstance(content, FunctionResultContent):
|
||||
# Tool result - shows writer's response
|
||||
result_text = content.result if isinstance(content.result, str) else str(content.result)
|
||||
if result_text.strip():
|
||||
print("\n[Function Result]", flush=True)
|
||||
print(f" Call ID: {content.call_id}", flush=True)
|
||||
print(f" Result: {result_text[:150]}{'...' if len(result_text) > 150 else ''}", flush=True)
|
||||
print()
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("=" * 60)
|
||||
print("Agent-as-Tool Pattern Comparison")
|
||||
print("=" * 60)
|
||||
print("Note: AutoGen requires parallel_tool_calls=False for AgentTool")
|
||||
print(" Agent Framework handles this automatically\n")
|
||||
await run_autogen()
|
||||
print()
|
||||
await run_agent_framework()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user