chore: import upstream snapshot with attribution
CodeQL / Analyze (csharp) (push) Waiting to run
CodeQL / Analyze (python) (push) Waiting to run
dotnet-build-and-test / dotnet-test-functions (push) Has been cancelled
dotnet-build-and-test / paths-filter (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Debug, windows-latest, net9.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, ubuntu-latest, net10.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, ubuntu-latest, net8.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, windows-latest, net472) (push) Has been cancelled
dotnet-build-and-test / dotnet-test (Release, integration, true, ubuntu-latest, net10.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-test (Release, integration, true, windows-latest, net472) (push) Has been cancelled
dotnet-build-and-test / dotnet-foundry-hosted-it (push) Has been cancelled
dotnet-build-and-test / dotnet-build-and-test-check (push) Has been cancelled
dotnet-build-and-test / Integration Test Report (push) Has been cancelled
CodeQL / Analyze (csharp) (push) Waiting to run
CodeQL / Analyze (python) (push) Waiting to run
dotnet-build-and-test / dotnet-test-functions (push) Has been cancelled
dotnet-build-and-test / paths-filter (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Debug, windows-latest, net9.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, ubuntu-latest, net10.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, ubuntu-latest, net8.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, windows-latest, net472) (push) Has been cancelled
dotnet-build-and-test / dotnet-test (Release, integration, true, ubuntu-latest, net10.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-test (Release, integration, true, windows-latest, net472) (push) Has been cancelled
dotnet-build-and-test / dotnet-foundry-hosted-it (push) Has been cancelled
dotnet-build-and-test / dotnet-build-and-test-check (push) Has been cancelled
dotnet-build-and-test / Integration Test Report (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,141 @@
|
||||
# /// script
|
||||
# requires-python = ">=3.10"
|
||||
# dependencies = [
|
||||
# "agent-framework-openai",
|
||||
# "agent-framework-orchestrations",
|
||||
# "semantic-kernel",
|
||||
# ]
|
||||
# ///
|
||||
# Run with any PEP 723 compatible runner, e.g.:
|
||||
# uv run samples/semantic-kernel-migration/orchestrations/concurrent_basic.py
|
||||
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
"""Side-by-side concurrent orchestrations for Agent Framework and Semantic Kernel."""
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Sequence
|
||||
from typing import cast
|
||||
|
||||
from agent_framework import Agent, Message
|
||||
from agent_framework.openai import OpenAIChatCompletionClient
|
||||
from agent_framework.orchestrations import ConcurrentBuilder
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from semantic_kernel.agents import ChatCompletionAgent, ConcurrentOrchestration
|
||||
from semantic_kernel.agents.runtime import InProcessRuntime
|
||||
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
|
||||
from semantic_kernel.contents import ChatMessageContent
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
PROMPT = "Explain the concept of temperature from multiple scientific perspectives."
|
||||
|
||||
|
||||
######################################################################
|
||||
# Semantic Kernel orchestration path
|
||||
######################################################################
|
||||
|
||||
|
||||
def build_semantic_kernel_agents() -> list[ChatCompletionAgent]:
|
||||
credential = AzureCliCredential()
|
||||
|
||||
physics_agent = ChatCompletionAgent(
|
||||
name="PhysicsExpert",
|
||||
instructions=("You are an expert in physics. Answer questions from a physics perspective."),
|
||||
service=AzureChatCompletion(credential=credential),
|
||||
)
|
||||
|
||||
chemistry_agent = ChatCompletionAgent(
|
||||
name="ChemistryExpert",
|
||||
instructions=("You are an expert in chemistry. Answer questions from a chemistry perspective."),
|
||||
service=AzureChatCompletion(credential=credential),
|
||||
)
|
||||
|
||||
return [physics_agent, chemistry_agent]
|
||||
|
||||
|
||||
async def run_semantic_kernel_example(prompt: str) -> Sequence[ChatMessageContent]:
|
||||
concurrent_orchestration = ConcurrentOrchestration(members=build_semantic_kernel_agents()) # type: ignore
|
||||
|
||||
runtime = InProcessRuntime()
|
||||
runtime.start()
|
||||
|
||||
try:
|
||||
orchestration_result = await concurrent_orchestration.invoke(task=prompt, runtime=runtime)
|
||||
final_value = await orchestration_result.get(timeout=60)
|
||||
if isinstance(final_value, ChatMessageContent):
|
||||
return [final_value]
|
||||
if isinstance(final_value, Sequence):
|
||||
return list(final_value)
|
||||
return []
|
||||
finally:
|
||||
await runtime.stop_when_idle()
|
||||
|
||||
|
||||
def _print_semantic_kernel_outputs(outputs: Sequence[ChatMessageContent]) -> None:
|
||||
if not outputs:
|
||||
print("No Semantic Kernel output.")
|
||||
return
|
||||
|
||||
print("===== Semantic Kernel Concurrent =====")
|
||||
for item in outputs:
|
||||
content = item.content or ""
|
||||
print(f"# {item.name}\n{content}\n")
|
||||
|
||||
|
||||
######################################################################
|
||||
# Agent Framework orchestration path
|
||||
######################################################################
|
||||
|
||||
|
||||
async def run_agent_framework_example(prompt: str) -> Sequence[list[Message]]:
|
||||
client = OpenAIChatCompletionClient(credential=AzureCliCredential())
|
||||
|
||||
physics = Agent(
|
||||
client=client,
|
||||
instructions=("You are an expert in physics. Answer questions from a physics perspective."),
|
||||
name="physics",
|
||||
)
|
||||
|
||||
chemistry = Agent(
|
||||
client=client,
|
||||
instructions=("You are an expert in chemistry. Answer questions from a chemistry perspective."),
|
||||
name="chemistry",
|
||||
)
|
||||
|
||||
workflow = ConcurrentBuilder(participants=[physics, chemistry]).build()
|
||||
|
||||
outputs: list[list[Message]] = []
|
||||
async for event in workflow.run(prompt, stream=True):
|
||||
if event.type == "output":
|
||||
outputs.append(cast(list[Message], event.data))
|
||||
|
||||
return outputs
|
||||
|
||||
|
||||
def _print_agent_framework_outputs(conversations: Sequence[Sequence[Message]]) -> None:
|
||||
if not conversations:
|
||||
print("No Agent Framework output.")
|
||||
return
|
||||
|
||||
print("===== Agent Framework Concurrent =====")
|
||||
for index, conversation in enumerate(conversations, start=1):
|
||||
print(f"--- Conversation {index} ---")
|
||||
for message in conversation:
|
||||
name = message.author_name or "assistant"
|
||||
print(f"[{name}] {message.text}")
|
||||
print()
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
agent_framework_outputs = await run_agent_framework_example(PROMPT)
|
||||
_print_agent_framework_outputs(agent_framework_outputs)
|
||||
|
||||
semantic_kernel_outputs = await run_semantic_kernel_example(PROMPT)
|
||||
_print_semantic_kernel_outputs(semantic_kernel_outputs)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,291 @@
|
||||
# /// script
|
||||
# requires-python = ">=3.10"
|
||||
# dependencies = [
|
||||
# "agent-framework-openai",
|
||||
# "agent-framework-orchestrations",
|
||||
# "semantic-kernel",
|
||||
# ]
|
||||
# ///
|
||||
# Run with any PEP 723 compatible runner, e.g.:
|
||||
# uv run samples/semantic-kernel-migration/orchestrations/group_chat.py
|
||||
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
"""Side-by-side group chat orchestrations for Agent Framework and Semantic Kernel."""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from collections.abc import Sequence
|
||||
from typing import Any, cast
|
||||
|
||||
from agent_framework import Agent, AgentResponseUpdate, Message
|
||||
from agent_framework.openai import OpenAIChatCompletionClient
|
||||
from agent_framework.orchestrations import GroupChatBuilder
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from semantic_kernel.agents import ChatCompletionAgent, GroupChatOrchestration
|
||||
from semantic_kernel.agents.orchestration.group_chat import (
|
||||
BooleanResult,
|
||||
GroupChatManager,
|
||||
MessageResult,
|
||||
StringResult,
|
||||
)
|
||||
from semantic_kernel.agents.runtime import InProcessRuntime
|
||||
from semantic_kernel.connectors.ai.chat_completion_client_base import ChatCompletionClientBase
|
||||
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
|
||||
from semantic_kernel.connectors.ai.prompt_execution_settings import PromptExecutionSettings
|
||||
from semantic_kernel.contents import AuthorRole, ChatHistory, ChatMessageContent
|
||||
from semantic_kernel.functions import KernelArguments
|
||||
from semantic_kernel.kernel import Kernel
|
||||
from semantic_kernel.prompt_template import KernelPromptTemplate, PromptTemplateConfig
|
||||
|
||||
if sys.version_info >= (3, 12):
|
||||
from typing import override # pragma: no cover
|
||||
else:
|
||||
from typing_extensions import override # pragma: no cover
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
|
||||
DISCUSSION_TOPIC = "What are the essential steps for launching a community hackathon?"
|
||||
|
||||
|
||||
######################################################################
|
||||
# Semantic Kernel orchestration path
|
||||
######################################################################
|
||||
|
||||
|
||||
def build_semantic_kernel_agents() -> list[ChatCompletionAgent]:
|
||||
credential = AzureCliCredential()
|
||||
|
||||
researcher = ChatCompletionAgent(
|
||||
name="Researcher",
|
||||
description="Collects background information and potential resources.",
|
||||
instructions=(
|
||||
"Gather concise facts or considerations that help plan a community hackathon. "
|
||||
"Keep your responses factual and scannable."
|
||||
),
|
||||
service=AzureChatCompletion(credential=credential),
|
||||
)
|
||||
|
||||
planner = ChatCompletionAgent(
|
||||
name="Planner",
|
||||
description="Synthesizes an actionable plan from available notes.",
|
||||
instructions=(
|
||||
"Use the running conversation to draft a structured action plan. Emphasize logistics and sequencing."
|
||||
),
|
||||
service=AzureChatCompletion(credential=credential),
|
||||
)
|
||||
|
||||
return [researcher, planner]
|
||||
|
||||
|
||||
class ChatCompletionGroupChatManager(GroupChatManager):
|
||||
"""Group chat manager that delegates orchestration decisions to an Azure OpenAI deployment."""
|
||||
|
||||
termination_prompt: str = (
|
||||
"You are coordinating a conversation about '{{$topic}}'. "
|
||||
"Decide if the discussion has produced a solid answer. "
|
||||
'Respond using JSON: {"result": true|false, "reason": "..."}.'
|
||||
)
|
||||
|
||||
selection_prompt: str = (
|
||||
"You are coordinating a conversation about '{{$topic}}'. "
|
||||
"Choose the next participant by returning JSON with keys (result, reason). "
|
||||
"The result must match one of: {{$participants}}."
|
||||
)
|
||||
|
||||
summary_prompt: str = (
|
||||
"You have just finished a discussion about '{{$topic}}'. "
|
||||
"Summarize the plan and highlight key takeaways. Return JSON with keys (result, reason) where "
|
||||
"result is the final response text."
|
||||
)
|
||||
|
||||
def __init__(self, *, topic: str, service: ChatCompletionClientBase, max_rounds: int | None = None) -> None:
|
||||
super().__init__(max_rounds=max_rounds)
|
||||
|
||||
self._round_robin_index = 0
|
||||
self._topic = topic
|
||||
self._service = service
|
||||
|
||||
async def _render_prompt(self, template: str, **kwargs: Any) -> str:
|
||||
prompt_template = KernelPromptTemplate(prompt_template_config=PromptTemplateConfig(template=template))
|
||||
return await prompt_template.render(Kernel(), arguments=KernelArguments(**kwargs))
|
||||
|
||||
@override
|
||||
async def should_request_user_input(self, chat_history: ChatHistory) -> BooleanResult:
|
||||
return BooleanResult(result=False, reason="This orchestration is fully automated.")
|
||||
|
||||
@override
|
||||
async def should_terminate(self, chat_history: ChatHistory) -> BooleanResult:
|
||||
rendered_prompt = await self._render_prompt(self.termination_prompt, topic=self._topic)
|
||||
chat_history.messages.insert(
|
||||
0,
|
||||
ChatMessageContent(role=AuthorRole.SYSTEM, content=rendered_prompt),
|
||||
)
|
||||
chat_history.add_message(
|
||||
ChatMessageContent(role=AuthorRole.USER, content="Decide if the discussion is complete."),
|
||||
)
|
||||
|
||||
response = await self._service.get_chat_message_content(
|
||||
chat_history,
|
||||
settings=PromptExecutionSettings(response_format=BooleanResult),
|
||||
)
|
||||
return BooleanResult.model_validate_json(response.content) # type: ignore
|
||||
|
||||
@override
|
||||
async def select_next_agent(
|
||||
self,
|
||||
chat_history: ChatHistory,
|
||||
participant_descriptions: dict[str, str],
|
||||
) -> StringResult:
|
||||
rendered_prompt = await self._render_prompt(
|
||||
self.selection_prompt,
|
||||
topic=self._topic,
|
||||
participants=", ".join(participant_descriptions.keys()),
|
||||
)
|
||||
chat_history.messages.insert(
|
||||
0,
|
||||
ChatMessageContent(role=AuthorRole.SYSTEM, content=rendered_prompt),
|
||||
)
|
||||
chat_history.add_message(
|
||||
ChatMessageContent(role=AuthorRole.USER, content="Pick the next participant to speak."),
|
||||
)
|
||||
|
||||
response = await self._service.get_chat_message_content(
|
||||
chat_history,
|
||||
settings=PromptExecutionSettings(response_format=StringResult),
|
||||
)
|
||||
result = StringResult.model_validate_json(response.content) # type: ignore
|
||||
if result.result not in participant_descriptions:
|
||||
raise RuntimeError(f"Unknown participant selected: {result.result}")
|
||||
return result
|
||||
|
||||
@override
|
||||
async def filter_results(self, chat_history: ChatHistory) -> MessageResult:
|
||||
rendered_prompt = await self._render_prompt(self.summary_prompt, topic=self._topic)
|
||||
chat_history.messages.insert(
|
||||
0,
|
||||
ChatMessageContent(role=AuthorRole.SYSTEM, content=rendered_prompt),
|
||||
)
|
||||
chat_history.add_message(
|
||||
ChatMessageContent(role=AuthorRole.USER, content="Summarize the plan."),
|
||||
)
|
||||
|
||||
response = await self._service.get_chat_message_content(
|
||||
chat_history,
|
||||
settings=PromptExecutionSettings(response_format=StringResult),
|
||||
)
|
||||
string_result = StringResult.model_validate_json(response.content) # type: ignore
|
||||
return MessageResult(
|
||||
result=ChatMessageContent(role=AuthorRole.ASSISTANT, content=string_result.result),
|
||||
reason=string_result.reason,
|
||||
)
|
||||
|
||||
|
||||
async def sk_agent_response_callback(message: ChatMessageContent | Sequence[ChatMessageContent]) -> None:
|
||||
if isinstance(message, ChatMessageContent):
|
||||
messages: Sequence[ChatMessageContent] = [message]
|
||||
elif isinstance(message, Sequence) and not isinstance(message, (str, bytes)):
|
||||
messages = list(message)
|
||||
else:
|
||||
messages = [cast(ChatMessageContent, message)]
|
||||
|
||||
for item in messages:
|
||||
print(f"# {item.name}\n{item.content}\n")
|
||||
|
||||
|
||||
async def run_semantic_kernel_example(task: str) -> str:
|
||||
credential = AzureCliCredential()
|
||||
orchestration = GroupChatOrchestration(
|
||||
members=build_semantic_kernel_agents(), # type: ignore
|
||||
manager=ChatCompletionGroupChatManager(
|
||||
topic=DISCUSSION_TOPIC,
|
||||
service=AzureChatCompletion(credential=credential),
|
||||
max_rounds=8,
|
||||
),
|
||||
agent_response_callback=sk_agent_response_callback,
|
||||
)
|
||||
|
||||
runtime = InProcessRuntime()
|
||||
runtime.start()
|
||||
|
||||
try:
|
||||
orchestration_result = await orchestration.invoke(task=task, runtime=runtime)
|
||||
final_message = await orchestration_result.get(timeout=30)
|
||||
if isinstance(final_message, ChatMessageContent):
|
||||
return final_message.content or ""
|
||||
return str(final_message)
|
||||
finally:
|
||||
await runtime.stop_when_idle()
|
||||
|
||||
|
||||
######################################################################
|
||||
# Agent Framework orchestration path
|
||||
######################################################################
|
||||
|
||||
|
||||
async def run_agent_framework_example(task: str) -> str:
|
||||
client = OpenAIChatCompletionClient(credential=AzureCliCredential())
|
||||
|
||||
researcher = Agent(
|
||||
name="Researcher",
|
||||
description="Collects background information and potential resources.",
|
||||
instructions=(
|
||||
"Gather concise facts or considerations that help plan a community hackathon. "
|
||||
"Keep your responses factual and scannable."
|
||||
),
|
||||
client=client,
|
||||
)
|
||||
|
||||
planner = Agent(
|
||||
name="Planner",
|
||||
description="Turns the collected notes into a concrete action plan.",
|
||||
instructions=("Propose a structured action plan that accounts for logistics, roles, and timeline."),
|
||||
client=client,
|
||||
)
|
||||
|
||||
workflow = GroupChatBuilder(
|
||||
participants=[researcher, planner],
|
||||
orchestrator_agent=Agent(client=client),
|
||||
max_rounds=8,
|
||||
intermediate_output_from=[researcher, planner],
|
||||
).build()
|
||||
|
||||
output_messages: list[Message] = []
|
||||
last_message_id: str | None = None
|
||||
async for event in workflow.run(task, stream=True):
|
||||
if event.type in ("intermediate", "output"):
|
||||
if isinstance(event.data, AgentResponseUpdate):
|
||||
if event.data.message_id != last_message_id:
|
||||
last_message_id = event.data.message_id
|
||||
print(f"{event.data.author_name}: {event.data.text}", end="")
|
||||
else:
|
||||
print(event.data.text, end="")
|
||||
else:
|
||||
output_messages.extend(cast(list[Message], event.data))
|
||||
for message in output_messages:
|
||||
print(f"[{message.author_name}] {message.text}")
|
||||
|
||||
if output_messages:
|
||||
return output_messages[-1].text
|
||||
|
||||
return ""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
task = "Kick off the group discussion."
|
||||
|
||||
print("===== Agent Framework Group Chat =====")
|
||||
af_response = await run_agent_framework_example(task)
|
||||
print(af_response or "No response returned.")
|
||||
print()
|
||||
|
||||
print("===== Semantic Kernel Group Chat =====")
|
||||
sk_response = await run_semantic_kernel_example(task)
|
||||
print(sk_response or "No response returned.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,311 @@
|
||||
# /// script
|
||||
# requires-python = ">=3.10"
|
||||
# dependencies = [
|
||||
# "agent-framework-openai",
|
||||
# "agent-framework-orchestrations",
|
||||
# "semantic-kernel",
|
||||
# ]
|
||||
# ///
|
||||
# Run with any PEP 723 compatible runner, e.g.:
|
||||
# uv run samples/semantic-kernel-migration/orchestrations/handoff.py
|
||||
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
"""Side-by-side handoff orchestrations for Semantic Kernel and Agent Framework."""
|
||||
|
||||
import asyncio
|
||||
from collections.abc import AsyncIterable, Callable, Iterator, Sequence
|
||||
|
||||
from agent_framework import (
|
||||
Agent,
|
||||
Message,
|
||||
WorkflowEvent,
|
||||
)
|
||||
from agent_framework.openai import OpenAIChatCompletionClient
|
||||
from agent_framework.orchestrations import HandoffAgentUserRequest, HandoffBuilder
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from semantic_kernel.agents import Agent as SKAgent
|
||||
from semantic_kernel.agents import ChatCompletionAgent, HandoffOrchestration, OrchestrationHandoffs
|
||||
from semantic_kernel.agents.runtime import InProcessRuntime
|
||||
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
|
||||
from semantic_kernel.contents import (
|
||||
AuthorRole,
|
||||
ChatMessageContent,
|
||||
FunctionCallContent,
|
||||
FunctionResultContent,
|
||||
StreamingChatMessageContent,
|
||||
)
|
||||
from semantic_kernel.functions import kernel_function
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
CUSTOMER_PROMPT = "I need help with order 12345. I want a replacement and need to know when it will arrive."
|
||||
SCRIPTED_RESPONSES = [
|
||||
"The item arrived damaged. I'd like a replacement shipped to the same address.",
|
||||
"Great! Can you confirm the shipping cost won't be charged again?",
|
||||
"Thanks for confirming!",
|
||||
]
|
||||
|
||||
|
||||
######################################################################
|
||||
# Semantic Kernel orchestration path
|
||||
######################################################################
|
||||
|
||||
|
||||
class OrderStatusPlugin:
|
||||
@kernel_function
|
||||
def check_order_status(self, order_id: str) -> str:
|
||||
return f"Order {order_id} is shipped and will arrive in 2-3 days."
|
||||
|
||||
|
||||
class OrderRefundPlugin:
|
||||
@kernel_function
|
||||
def process_refund(self, order_id: str, reason: str) -> str:
|
||||
return f"Refund for order {order_id} has been processed successfully (reason: {reason})."
|
||||
|
||||
|
||||
class OrderReturnPlugin:
|
||||
@kernel_function
|
||||
def process_return(self, order_id: str, reason: str) -> str:
|
||||
return f"Return for order {order_id} has been processed successfully (reason: {reason})."
|
||||
|
||||
|
||||
def build_semantic_kernel_agents() -> tuple[list[SKAgent], OrchestrationHandoffs]:
|
||||
credential = AzureCliCredential()
|
||||
|
||||
triage = ChatCompletionAgent(
|
||||
name="TriageAgent",
|
||||
description="Customer support triage specialist.",
|
||||
instructions="Greet the customer, collect intent, and hand off to the right specialist.",
|
||||
service=AzureChatCompletion(credential=credential),
|
||||
)
|
||||
refund = ChatCompletionAgent(
|
||||
name="RefundAgent",
|
||||
description="Handles refunds.",
|
||||
instructions="Process refund requests.",
|
||||
service=AzureChatCompletion(credential=credential),
|
||||
plugins=[OrderRefundPlugin()],
|
||||
)
|
||||
order_status = ChatCompletionAgent(
|
||||
name="OrderStatusAgent",
|
||||
description="Looks up order status.",
|
||||
instructions="Provide shipping timelines and tracking information.",
|
||||
service=AzureChatCompletion(credential=credential),
|
||||
plugins=[OrderStatusPlugin()],
|
||||
)
|
||||
order_return = ChatCompletionAgent(
|
||||
name="OrderReturnAgent",
|
||||
description="Handles returns.",
|
||||
instructions="Coordinate order returns.",
|
||||
service=AzureChatCompletion(credential=credential),
|
||||
plugins=[OrderReturnPlugin()],
|
||||
)
|
||||
|
||||
handoffs = (
|
||||
OrchestrationHandoffs()
|
||||
.add_many(
|
||||
source_agent=triage.name,
|
||||
target_agents={
|
||||
refund.name: "Route refund-related requests here.",
|
||||
order_status.name: "Route shipping questions here.",
|
||||
order_return.name: "Route return-related requests here.",
|
||||
},
|
||||
)
|
||||
.add(refund.name, triage.name, "Return to triage for non-refund issues.")
|
||||
.add(order_status.name, triage.name, "Return to triage for non-status issues.")
|
||||
.add(order_return.name, triage.name, "Return to triage for non-return issues.")
|
||||
)
|
||||
|
||||
return [triage, refund, order_status, order_return], handoffs
|
||||
|
||||
|
||||
_sk_new_message = True
|
||||
|
||||
|
||||
def _sk_streaming_callback(message: StreamingChatMessageContent, is_final: bool) -> None:
|
||||
"""Display SK agent messages as they stream."""
|
||||
|
||||
global _sk_new_message
|
||||
if _sk_new_message:
|
||||
print(f"{message.name}: ", end="", flush=True)
|
||||
_sk_new_message = False
|
||||
|
||||
if message.content:
|
||||
print(message.content, end="", flush=True)
|
||||
|
||||
for item in message.items:
|
||||
if isinstance(item, FunctionCallContent):
|
||||
print(f"[tool call: {item.name}({item.arguments})]", end="", flush=True)
|
||||
if isinstance(item, FunctionResultContent):
|
||||
print(f"[tool result: {item.result}]", end="", flush=True)
|
||||
|
||||
if is_final:
|
||||
print()
|
||||
_sk_new_message = True
|
||||
|
||||
|
||||
def _make_sk_human_responder(script: Iterator[str]) -> Callable[[], ChatMessageContent]:
|
||||
def _responder() -> ChatMessageContent:
|
||||
try:
|
||||
user_text = next(script)
|
||||
except StopIteration:
|
||||
user_text = "Thanks, that's all."
|
||||
print(f"[User]: {user_text}")
|
||||
return ChatMessageContent(role=AuthorRole.USER, content=user_text)
|
||||
|
||||
return _responder
|
||||
|
||||
|
||||
async def run_semantic_kernel_example(initial_task: str, scripted_responses: Sequence[str]) -> str:
|
||||
agents, handoffs = build_semantic_kernel_agents()
|
||||
response_iter = iter(scripted_responses)
|
||||
|
||||
orchestration = HandoffOrchestration(
|
||||
members=agents,
|
||||
handoffs=handoffs,
|
||||
streaming_agent_response_callback=_sk_streaming_callback,
|
||||
human_response_function=_make_sk_human_responder(response_iter),
|
||||
)
|
||||
|
||||
runtime = InProcessRuntime()
|
||||
runtime.start()
|
||||
|
||||
try:
|
||||
orchestration_result = await orchestration.invoke(task=initial_task, runtime=runtime)
|
||||
final_message = await orchestration_result.get(timeout=30)
|
||||
if isinstance(final_message, ChatMessageContent):
|
||||
return final_message.content or ""
|
||||
return str(final_message)
|
||||
finally:
|
||||
await runtime.stop_when_idle()
|
||||
|
||||
|
||||
######################################################################
|
||||
# Agent Framework orchestration path
|
||||
######################################################################
|
||||
|
||||
|
||||
def _create_af_agents(client: OpenAIChatCompletionClient):
|
||||
triage = Agent(
|
||||
client=client,
|
||||
name="triage_agent",
|
||||
instructions=(
|
||||
"You are a customer support triage agent. Route requests:\n"
|
||||
"- handoff_to_refund_agent for refunds\n"
|
||||
"- handoff_to_order_status_agent for shipping/timeline questions\n"
|
||||
"- handoff_to_order_return_agent for returns"
|
||||
),
|
||||
require_per_service_call_history_persistence=True,
|
||||
)
|
||||
refund = Agent(
|
||||
client=client,
|
||||
name="refund_agent",
|
||||
instructions=(
|
||||
"Handle refunds. Ask for order id and reason. If shipping info is needed, hand off to order_status_agent."
|
||||
),
|
||||
require_per_service_call_history_persistence=True,
|
||||
)
|
||||
status = Agent(
|
||||
client=client,
|
||||
name="order_status_agent",
|
||||
instructions=(
|
||||
"Provide order status, tracking, and timelines. If billing questions appear, hand off to refund_agent."
|
||||
),
|
||||
require_per_service_call_history_persistence=True,
|
||||
)
|
||||
returns = Agent(
|
||||
client=client,
|
||||
name="order_return_agent",
|
||||
instructions=(
|
||||
"Coordinate returns, confirm addresses, and summarize next steps. Hand off to triage_agent if unsure."
|
||||
),
|
||||
require_per_service_call_history_persistence=True,
|
||||
)
|
||||
return triage, refund, status, returns
|
||||
|
||||
|
||||
async def _drain_events(stream: AsyncIterable[WorkflowEvent]) -> list[WorkflowEvent]:
|
||||
return [event async for event in stream]
|
||||
|
||||
|
||||
def _collect_handoff_requests(events: list[WorkflowEvent]) -> list[WorkflowEvent]:
|
||||
requests: list[WorkflowEvent] = []
|
||||
for event in events:
|
||||
if event.type == "request_info" and isinstance(event.data, HandoffAgentUserRequest):
|
||||
requests.append(event)
|
||||
return requests
|
||||
|
||||
|
||||
def _extract_final_conversation(events: list[WorkflowEvent]) -> list[Message]:
|
||||
for event in events:
|
||||
if event.type == "output":
|
||||
return event.data
|
||||
return []
|
||||
|
||||
|
||||
async def run_agent_framework_example(initial_task: str, scripted_responses: Sequence[str]) -> str:
|
||||
client = OpenAIChatCompletionClient(credential=AzureCliCredential())
|
||||
triage, refund, status, returns = _create_af_agents(client)
|
||||
|
||||
workflow = (
|
||||
HandoffBuilder(
|
||||
name="sk_af_handoff_migration",
|
||||
participants=[triage, refund, status, returns],
|
||||
termination_condition=lambda conv: sum(1 for m in conv if m.role == "user") >= 4,
|
||||
)
|
||||
.with_start_agent(triage)
|
||||
.add_handoff(triage, [refund, status, returns])
|
||||
.add_handoff(refund, [status, triage])
|
||||
.add_handoff(status, [refund, triage])
|
||||
.add_handoff(returns, [triage])
|
||||
.build()
|
||||
)
|
||||
|
||||
events = await _drain_events(workflow.run(initial_task, stream=True))
|
||||
pending = _collect_handoff_requests(events)
|
||||
scripted_iter = iter(scripted_responses)
|
||||
|
||||
final_events = events
|
||||
while pending:
|
||||
try:
|
||||
user_reply = next(scripted_iter)
|
||||
except StopIteration:
|
||||
user_reply = "Thanks, that's all."
|
||||
responses = {request.request_id: [Message(role="user", contents=[user_reply])] for request in pending}
|
||||
final_events = await _drain_events(workflow.run(stream=True, responses=responses))
|
||||
pending = _collect_handoff_requests(final_events)
|
||||
|
||||
conversation = _extract_final_conversation(final_events)
|
||||
if not conversation:
|
||||
return ""
|
||||
|
||||
# Render final transcript succinctly.
|
||||
lines: list[str] = []
|
||||
for message in conversation:
|
||||
text = message.text or ""
|
||||
if not text.strip():
|
||||
continue
|
||||
speaker = message.author_name or message.role
|
||||
lines.append(f"{speaker}: {text}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
######################################################################
|
||||
# Console entry point
|
||||
######################################################################
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("===== Agent Framework Handoff =====")
|
||||
af_transcript = await run_agent_framework_example(CUSTOMER_PROMPT, SCRIPTED_RESPONSES)
|
||||
print(af_transcript or "No output produced.")
|
||||
print()
|
||||
|
||||
print("===== Semantic Kernel Handoff =====")
|
||||
sk_result = await run_semantic_kernel_example(CUSTOMER_PROMPT, SCRIPTED_RESPONSES)
|
||||
print(sk_result or "No output produced.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,211 @@
|
||||
# /// script
|
||||
# requires-python = ">=3.10"
|
||||
# dependencies = [
|
||||
# "agent-framework-openai",
|
||||
# "agent-framework-orchestrations",
|
||||
# "semantic-kernel",
|
||||
# ]
|
||||
# ///
|
||||
# Run with any PEP 723 compatible runner, e.g.:
|
||||
# uv run samples/semantic-kernel-migration/orchestrations/magentic.py
|
||||
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
"""Side-by-side Magentic orchestrations for Agent Framework and Semantic Kernel."""
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Sequence
|
||||
from typing import cast
|
||||
|
||||
from agent_framework import Agent, AgentResponseUpdate, Message
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
from agent_framework.orchestrations import MagenticBuilder
|
||||
from dotenv import load_dotenv
|
||||
from semantic_kernel.agents import (
|
||||
ChatCompletionAgent,
|
||||
MagenticOrchestration,
|
||||
OpenAIAssistantAgent,
|
||||
StandardMagenticManager,
|
||||
)
|
||||
from semantic_kernel.agents.runtime import InProcessRuntime
|
||||
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion, OpenAISettings
|
||||
from semantic_kernel.contents import ChatMessageContent
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
PROMPT = (
|
||||
"I am preparing a report on the energy efficiency of different machine learning model architectures. "
|
||||
"Compare the estimated training and inference energy consumption of ResNet-50, BERT-base, and GPT-2 "
|
||||
"on standard datasets (e.g., ImageNet for ResNet, GLUE for BERT, WebText for GPT-2). "
|
||||
"Then, estimate the CO2 emissions associated with each, assuming training on an Azure Standard_NC6s_v3 VM "
|
||||
"for 24 hours. Provide tables for clarity, and recommend the most energy-efficient model per task type "
|
||||
"(image classification, text classification, and text generation)."
|
||||
)
|
||||
|
||||
|
||||
######################################################################
|
||||
# Semantic Kernel orchestration path
|
||||
######################################################################
|
||||
|
||||
|
||||
async def build_semantic_kernel_agents() -> list[ChatCompletionAgent | OpenAIAssistantAgent]:
|
||||
research_agent = ChatCompletionAgent(
|
||||
name="ResearchAgent",
|
||||
description="A helpful assistant with access to web search. Ask it to perform web searches.",
|
||||
instructions=(
|
||||
"You are a Researcher. You find information without additional computation or quantitative analysis."
|
||||
),
|
||||
service=OpenAIChatCompletion(ai_model="gpt-4o-mini-search-preview"),
|
||||
)
|
||||
|
||||
client = OpenAIAssistantAgent.create_client()
|
||||
code_interpreter_tool, code_interpreter_tool_resources = OpenAIAssistantAgent.configure_code_interpreter_tool()
|
||||
openai_settings = OpenAISettings()
|
||||
model = openai_settings.chat_model if openai_settings.chat_model else "gpt-5"
|
||||
definition = await client.beta.assistants.create( # pyright: ignore[reportDeprecated]
|
||||
model=model,
|
||||
name="CoderAgent",
|
||||
description="A helpful assistant that writes and executes code to process and analyze data.",
|
||||
instructions="You solve questions using code. Please provide detailed analysis and computation process.",
|
||||
tools=code_interpreter_tool,
|
||||
tool_resources=code_interpreter_tool_resources,
|
||||
)
|
||||
coder_agent = OpenAIAssistantAgent(
|
||||
client=client,
|
||||
definition=definition,
|
||||
)
|
||||
|
||||
return [research_agent, coder_agent]
|
||||
|
||||
|
||||
def sk_agent_response_callback(
|
||||
message: ChatMessageContent | Sequence[ChatMessageContent],
|
||||
) -> None:
|
||||
if isinstance(message, ChatMessageContent):
|
||||
messages: Sequence[ChatMessageContent] = [message]
|
||||
elif isinstance(message, Sequence) and not isinstance(message, (str, bytes)):
|
||||
messages = [item for item in message if isinstance(item, ChatMessageContent)]
|
||||
else:
|
||||
messages = []
|
||||
|
||||
for item in messages:
|
||||
content = item.content or ""
|
||||
print(f"**{item.name}**\n{content}\n")
|
||||
|
||||
|
||||
async def run_semantic_kernel_example(prompt: str) -> Sequence[ChatMessageContent]:
|
||||
agents = await build_semantic_kernel_agents()
|
||||
magentic_orchestration = MagenticOrchestration(
|
||||
members=agents, # type: ignore
|
||||
manager=StandardMagenticManager(chat_completion_service=OpenAIChatCompletion()),
|
||||
agent_response_callback=sk_agent_response_callback,
|
||||
)
|
||||
|
||||
runtime = InProcessRuntime()
|
||||
runtime.start()
|
||||
|
||||
try:
|
||||
orchestration_result = await magentic_orchestration.invoke(task=prompt, runtime=runtime)
|
||||
value = await orchestration_result.get()
|
||||
if isinstance(value, ChatMessageContent):
|
||||
return [value]
|
||||
if isinstance(value, Sequence) and not isinstance(value, (str, bytes)):
|
||||
return [item for item in value if isinstance(item, ChatMessageContent)]
|
||||
return []
|
||||
finally:
|
||||
await runtime.stop_when_idle()
|
||||
|
||||
|
||||
def _print_semantic_kernel_outputs(outputs: Sequence[ChatMessageContent]) -> None:
|
||||
if not outputs:
|
||||
print("No Semantic Kernel output.")
|
||||
return
|
||||
|
||||
print("===== Semantic Kernel Magentic =====")
|
||||
for item in outputs:
|
||||
content = item.content or ""
|
||||
print(f"**{item.name}**\n{content}\n")
|
||||
|
||||
|
||||
######################################################################
|
||||
# Agent Framework orchestration path
|
||||
######################################################################
|
||||
|
||||
|
||||
async def run_agent_framework_example(prompt: str) -> str | None:
|
||||
researcher = Agent(
|
||||
name="ResearcherAgent",
|
||||
description="Specialist in research and information gathering",
|
||||
instructions=(
|
||||
"You are a Researcher. You find information without additional computation or quantitative analysis."
|
||||
),
|
||||
client=OpenAIChatClient(model="gpt-4o-mini-search-preview"),
|
||||
)
|
||||
|
||||
# Create code interpreter tool using static method
|
||||
coder_client = OpenAIChatClient()
|
||||
code_interpreter_tool = OpenAIChatClient.get_code_interpreter_tool()
|
||||
|
||||
coder = Agent(
|
||||
name="CoderAgent",
|
||||
description="A helpful assistant that writes and executes code to process and analyze data.",
|
||||
instructions="You solve questions using code. Please provide detailed analysis and computation process.",
|
||||
client=coder_client,
|
||||
tools=[code_interpreter_tool],
|
||||
)
|
||||
|
||||
# Create a manager agent for orchestration
|
||||
manager_agent = Agent(
|
||||
name="MagenticManager",
|
||||
description="Orchestrator that coordinates the research and coding workflow",
|
||||
instructions="You coordinate a team to complete complex tasks efficiently.",
|
||||
client=OpenAIChatClient(),
|
||||
)
|
||||
|
||||
workflow = MagenticBuilder(
|
||||
participants=[researcher, coder],
|
||||
manager_agent=manager_agent, # type: ignore
|
||||
intermediate_output_from=[researcher, coder],
|
||||
).build()
|
||||
|
||||
output_messages: list[Message] = []
|
||||
last_message_id: str | None = None
|
||||
async for event in workflow.run(prompt, stream=True):
|
||||
if event.type in ("intermediate", "output"):
|
||||
if isinstance(event.data, AgentResponseUpdate):
|
||||
if event.data.message_id != last_message_id:
|
||||
last_message_id = event.data.message_id
|
||||
print(f"{event.data.author_name}: {event.data.text}", end="")
|
||||
else:
|
||||
print(event.data.text, end="")
|
||||
else:
|
||||
output_messages.extend(cast(list[Message], event.data))
|
||||
for message in output_messages:
|
||||
print(f"[{message.author_name}] {message.text}")
|
||||
|
||||
if output_messages:
|
||||
return output_messages[-1].text
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _print_agent_framework_output(result: str | None) -> None:
|
||||
if result is None:
|
||||
print("No Agent Framework output.")
|
||||
return
|
||||
|
||||
print("===== Agent Framework Magentic =====")
|
||||
print(result)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
agent_framework_result = await run_agent_framework_example(PROMPT)
|
||||
_print_agent_framework_output(agent_framework_result)
|
||||
|
||||
semantic_kernel_outputs = await run_semantic_kernel_example(PROMPT)
|
||||
_print_semantic_kernel_outputs(semantic_kernel_outputs)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,146 @@
|
||||
# /// script
|
||||
# requires-python = ">=3.10"
|
||||
# dependencies = [
|
||||
# "agent-framework-openai",
|
||||
# "agent-framework-orchestrations",
|
||||
# "semantic-kernel",
|
||||
# ]
|
||||
# ///
|
||||
# Run with any PEP 723 compatible runner, e.g.:
|
||||
# uv run samples/semantic-kernel-migration/orchestrations/sequential.py
|
||||
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
"""Side-by-side sequential orchestrations for Agent Framework and Semantic Kernel."""
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Sequence
|
||||
from typing import cast
|
||||
|
||||
from agent_framework import Agent, Message
|
||||
from agent_framework.openai import OpenAIChatCompletionClient
|
||||
from agent_framework.orchestrations import SequentialBuilder
|
||||
from azure.identity import AzureCliCredential
|
||||
from dotenv import load_dotenv
|
||||
from semantic_kernel.agents import Agent as SKAgent
|
||||
from semantic_kernel.agents import ChatCompletionAgent, SequentialOrchestration
|
||||
from semantic_kernel.agents.runtime import InProcessRuntime
|
||||
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
|
||||
from semantic_kernel.contents import ChatMessageContent
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
PROMPT = "Write a tagline for a budget-friendly eBike."
|
||||
|
||||
|
||||
######################################################################
|
||||
# Semantic Kernel orchestration path
|
||||
######################################################################
|
||||
|
||||
|
||||
def build_semantic_kernel_agents() -> list[SKAgent]:
|
||||
credential = AzureCliCredential()
|
||||
|
||||
writer_agent = ChatCompletionAgent(
|
||||
name="WriterAgent",
|
||||
instructions=("You are a concise copywriter. Provide a single, punchy marketing sentence based on the prompt."),
|
||||
service=AzureChatCompletion(credential=credential),
|
||||
)
|
||||
|
||||
reviewer_agent = ChatCompletionAgent(
|
||||
name="ReviewerAgent",
|
||||
instructions=("You are a thoughtful reviewer. Give brief feedback on the previous assistant message."),
|
||||
service=AzureChatCompletion(credential=credential),
|
||||
)
|
||||
|
||||
return [writer_agent, reviewer_agent]
|
||||
|
||||
|
||||
async def sk_agent_response_callback(
|
||||
message: ChatMessageContent | Sequence[ChatMessageContent],
|
||||
) -> None:
|
||||
if isinstance(message, ChatMessageContent):
|
||||
messages: Sequence[ChatMessageContent] = [message]
|
||||
elif isinstance(message, Sequence) and not isinstance(message, (str, bytes)):
|
||||
messages = list(message)
|
||||
else:
|
||||
messages = [cast(ChatMessageContent, message)]
|
||||
|
||||
for item in messages:
|
||||
content = item.content or ""
|
||||
print(f"# {item.name}\n{content}\n")
|
||||
|
||||
|
||||
######################################################################
|
||||
# Agent Framework orchestration path
|
||||
######################################################################
|
||||
|
||||
|
||||
async def run_agent_framework_example(prompt: str) -> list[Message]:
|
||||
client = OpenAIChatCompletionClient(credential=AzureCliCredential())
|
||||
|
||||
writer = Agent(
|
||||
client=client,
|
||||
instructions=("You are a concise copywriter. Provide a single, punchy marketing sentence based on the prompt."),
|
||||
name="writer",
|
||||
)
|
||||
|
||||
reviewer = Agent(
|
||||
client=client,
|
||||
instructions=("You are a thoughtful reviewer. Give brief feedback on the previous assistant message."),
|
||||
name="reviewer",
|
||||
)
|
||||
|
||||
workflow = SequentialBuilder(participants=[writer, reviewer]).build()
|
||||
|
||||
conversation_outputs: list[list[Message]] = []
|
||||
async for event in workflow.run(prompt, stream=True):
|
||||
if event.type == "output":
|
||||
conversation_outputs.append(cast(list[Message], event.data))
|
||||
|
||||
return conversation_outputs[-1] if conversation_outputs else []
|
||||
|
||||
|
||||
async def run_semantic_kernel_example(prompt: str) -> str:
|
||||
sequential_orchestration = SequentialOrchestration(
|
||||
members=build_semantic_kernel_agents(),
|
||||
agent_response_callback=sk_agent_response_callback,
|
||||
)
|
||||
|
||||
runtime = InProcessRuntime()
|
||||
runtime.start()
|
||||
|
||||
try:
|
||||
orchestration_result = await sequential_orchestration.invoke(task=prompt, runtime=runtime)
|
||||
final_message = await orchestration_result.get(timeout=20)
|
||||
if isinstance(final_message, ChatMessageContent):
|
||||
return final_message.content or ""
|
||||
return str(final_message)
|
||||
finally:
|
||||
await runtime.stop_when_idle()
|
||||
|
||||
|
||||
def _format_conversation(conversation: list[Message]) -> None:
|
||||
if not conversation:
|
||||
print("No Agent Framework output.")
|
||||
return
|
||||
|
||||
print("===== Agent Framework Sequential =====")
|
||||
for index, message in enumerate(conversation, start=1):
|
||||
name = message.author_name or ("assistant" if message.role == "assistant" else "user")
|
||||
print(f"{'-' * 60}\n{index:02d} [{name}]\n{message.text}")
|
||||
print()
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
conversation = await run_agent_framework_example(PROMPT)
|
||||
_format_conversation(conversation)
|
||||
|
||||
print("===== Semantic Kernel Sequential =====")
|
||||
final_text = await run_semantic_kernel_example(PROMPT)
|
||||
print(final_text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user