Python: Fixed SK migration samples (#4046)

* Fixed sk migration provider samples

* Fixes to SK migration samples
This commit is contained in:
Dmytro Struk
2026-02-18 12:20:21 -08:00
committed by GitHub
Unverified
parent aab80d9ed9
commit c23bc1371c
17 changed files with 96 additions and 101 deletions
@@ -25,7 +25,7 @@ async def run_semantic_kernel() -> None:
async with AzureCliCredential() as credential, AzureAIAgent.create_client(credential=credential) as client:
settings = AzureAIAgentSettings() # Reads env vars for region/deployment.
# SK builds the remote agent definition then wraps it with AzureAIAgent.
definition = await client.agents.as_agent(
definition = await client.agents.create_agent(
model=settings.model_deployment_name,
name="Support",
instructions="Answer customer questions in one paragraph.",
@@ -25,7 +25,7 @@ async def run_semantic_kernel() -> None:
async with AzureCliCredential() as credential, AzureAIAgent.create_client(credential=credential) as client:
settings = AzureAIAgentSettings()
# Register the hosted code interpreter tool with the remote agent.
definition = await client.agents.as_agent(
definition = await client.agents.create_agent(
model=settings.model_deployment_name,
name="Analyst",
instructions="Use the code interpreter for numeric work.",
@@ -46,9 +46,7 @@ async def run_agent_framework() -> None:
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
# Create a client to access hosted tool factory methods
client = AzureAIAgentClient(agents_client=provider._agents_client)
code_interpreter_tool = client.get_code_interpreter_tool()
code_interpreter_tool = AzureAIAgentClient.get_code_interpreter_tool()
agent = await provider.create_agent(
name="Analyst",
@@ -19,7 +19,7 @@ async def run_semantic_kernel() -> None:
async with AzureCliCredential() as credential, AzureAIAgent.create_client(credential=credential) as client:
settings = AzureAIAgentSettings()
definition = await client.agents.as_agent(
definition = await client.agents.create_agent(
model=settings.model_deployment_name,
name="Planner",
instructions="Track follow-up questions within the same thread.",
@@ -43,7 +43,7 @@ async def run_semantic_kernel() -> None:
async def run_agent_framework() -> None:
from agent_framework._tools import tool
from agent_framework import tool
from agent_framework.openai import OpenAIChatClient
@tool(name="specials", description="List daily specials")
@@ -46,11 +46,12 @@ async def run_agent_framework() -> None:
instructions="Answer questions in one concise paragraph.",
model=ASSISTANT_MODEL,
) as assistant_agent:
reply = await assistant_agent.run("What is the capital of Denmark?")
session = assistant_agent.create_session()
reply = await assistant_agent.run("What is the capital of Denmark?", session=session)
print("[AF]", reply.text)
follow_up = await assistant_agent.run(
"How many residents live there?",
session=assistant_agent.create_session(),
session=session,
)
print("[AF][follow-up]", follow_up.text)
@@ -23,7 +23,7 @@ async def run_semantic_kernel() -> None:
# Enable the hosted code interpreter tool on the assistant definition.
definition = await client.beta.assistants.create(
model=OpenAISettings().chat_deployment_name,
model=OpenAISettings().chat_model_id,
name="CodeRunner",
instructions="Run the provided request as code and return the result.",
tools=code_interpreter_tool,
@@ -34,7 +34,7 @@ async def run_semantic_kernel() -> None:
class WeatherPlugin:
@kernel_function(name="get_forecast", description="Look up the forecast for a city and day.")
async def fake_weather_lookup(city: str, day: str) -> dict[str, Any]:
async def fake_weather_lookup(self, city: str, day: str) -> dict[str, Any]:
"""Pretend to call a weather service."""
return {
"city": city,
@@ -50,9 +50,8 @@ async def run_semantic_kernel() -> None:
model=ASSISTANT_MODEL,
name="WeatherHelper",
instructions="Call get_forecast to fetch weather details.",
plugins=[WeatherPlugin()],
)
agent = OpenAIAssistantAgent(client=client, definition=definition)
agent = OpenAIAssistantAgent(client=client, definition=definition, plugins=[WeatherPlugin()])
thread: AssistantAgentThread | None = None
response = await agent.get_response(
@@ -64,7 +63,7 @@ async def run_semantic_kernel() -> None:
async def run_agent_framework() -> None:
from agent_framework._tools import tool
from agent_framework import tool
from agent_framework.openai import OpenAIAssistantsClient
@tool(
@@ -14,24 +14,19 @@ import asyncio
async def run_semantic_kernel() -> None:
from azure.identity import AzureCliCredential
from semantic_kernel.agents import AzureResponsesAgent
from semantic_kernel.connectors.ai.open_ai import AzureOpenAISettings
from semantic_kernel.agents import OpenAIResponsesAgent
from semantic_kernel.connectors.ai.open_ai import OpenAISettings
credential = AzureCliCredential()
try:
client = AzureResponsesAgent.create_client(credential=credential)
# SK response agents wrap Azure OpenAI's hosted Responses API.
agent = AzureResponsesAgent(
ai_model_id=AzureOpenAISettings().responses_deployment_name,
client=client,
instructions="Answer in one concise sentence.",
name="Expert",
)
response = await agent.get_response("Why is the sky blue?")
print("[SK]", response.message.content)
finally:
await credential.close()
client = OpenAIResponsesAgent.create_client()
# SK response agents wrap OpenAI's hosted Responses API.
agent = OpenAIResponsesAgent(
ai_model_id=OpenAISettings().responses_model_id,
client=client,
instructions="Answer in one concise sentence.",
name="Expert",
)
response = await agent.get_response("Why is the sky blue?")
print("[SK]", response.message.content)
async def run_agent_framework() -> None:
@@ -14,9 +14,8 @@ import asyncio
async def run_semantic_kernel() -> None:
from azure.identity import AzureCliCredential
from semantic_kernel.agents import AzureResponsesAgent
from semantic_kernel.connectors.ai.open_ai import AzureOpenAISettings
from semantic_kernel.agents import OpenAIResponsesAgent
from semantic_kernel.connectors.ai.open_ai import OpenAISettings
from semantic_kernel.functions import kernel_function
class MathPlugin:
@@ -24,26 +23,22 @@ async def run_semantic_kernel() -> None:
def add(self, a: float, b: float) -> float:
return a + b
credential = AzureCliCredential()
try:
client = AzureResponsesAgent.create_client(credential=credential)
# Plugins advertise callable tools to the Responses agent.
agent = AzureResponsesAgent(
ai_model_id=AzureOpenAISettings().responses_deployment_name,
client=client,
instructions="Use the add tool when math is required.",
name="MathExpert",
plugins=[MathPlugin()],
)
response = await agent.get_response("Use add(41, 1) and explain the result.")
print("[SK]", response.message.content)
finally:
await credential.close()
client = OpenAIResponsesAgent.create_client()
# Plugins advertise callable tools to the Responses agent.
agent = OpenAIResponsesAgent(
ai_model_id=OpenAISettings().responses_model_id,
client=client,
instructions="Use the add tool when math is required.",
name="MathExpert",
plugins=[MathPlugin()],
)
response = await agent.get_response("Use add(41, 1) and explain the result.")
print("[SK]", response.message.content)
async def run_agent_framework() -> None:
from agent_framework import Agent
from agent_framework._tools import tool
from agent_framework import tool
from agent_framework.openai import OpenAIResponsesClient
@tool(name="add", description="Add two numbers")
@@ -22,28 +22,22 @@ class ReleaseBrief(BaseModel):
async def run_semantic_kernel() -> None:
from azure.identity import AzureCliCredential
from semantic_kernel.agents import AzureResponsesAgent
from semantic_kernel.connectors.ai.open_ai import AzureOpenAISettings
from semantic_kernel.agents import OpenAIResponsesAgent
from semantic_kernel.connectors.ai.open_ai import OpenAISettings
credential = AzureCliCredential()
try:
client = AzureResponsesAgent.create_client(credential=credential)
# response_format requests schema-constrained output from the model.
agent = AzureResponsesAgent(
ai_model_id=AzureOpenAISettings().responses_deployment_name,
client=client,
instructions="Return launch briefs as structured JSON.",
name="ProductMarketer",
text=AzureResponsesAgent.configure_response_format(ReleaseBrief),
)
response = await agent.get_response(
"Draft a launch brief for the Contoso Note app.",
response_format=ReleaseBrief,
)
print("[SK]", response.message.content)
finally:
await credential.close()
client = OpenAIResponsesAgent.create_client()
# response_format requests schema-constrained output from the model.
agent = OpenAIResponsesAgent(
ai_model_id=OpenAISettings().responses_model_id,
client=client,
instructions="Return launch briefs as structured JSON.",
name="ProductMarketer",
text=OpenAIResponsesAgent.configure_response_format(ReleaseBrief),
)
response = await agent.get_response(
"Draft a launch brief for the Contoso Note app.",
)
print("[SK]", response.message.content)
async def run_agent_framework() -> None:
@@ -32,7 +32,7 @@ PROMPT = "Explain the concept of temperature from multiple scientific perspectiv
######################################################################
def build_semantic_kernel_agents() -> list[Agent]:
def build_semantic_kernel_agents() -> list[ChatCompletionAgent]:
credential = AzureCliCredential()
physics_agent = ChatCompletionAgent(
@@ -20,7 +20,7 @@ from agent_framework import Agent, Message
from agent_framework.azure import AzureOpenAIChatClient, AzureOpenAIResponsesClient
from agent_framework.orchestrations import GroupChatBuilder
from azure.identity import AzureCliCredential
from semantic_kernel.agents import Agent, ChatCompletionAgent, GroupChatOrchestration
from semantic_kernel.agents import ChatCompletionAgent, GroupChatOrchestration
from semantic_kernel.agents.orchestration.group_chat import (
BooleanResult,
GroupChatManager,
@@ -50,7 +50,7 @@ DISCUSSION_TOPIC = "What are the essential steps for launching a community hacka
######################################################################
def build_semantic_kernel_agents() -> list[Agent]:
def build_semantic_kernel_agents() -> list[ChatCompletionAgent]:
credential = AzureCliCredential()
researcher = ChatCompletionAgent(
@@ -82,25 +82,25 @@ class ChatCompletionGroupChatManager(GroupChatManager):
topic: str
termination_prompt: str = (
"You are coordinating a conversation about '{{topic}}'. "
"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}}'. "
"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}}."
"The result must match one of: {{$participants}}."
)
summary_prompt: str = (
"You have just finished a discussion about '{{topic}}'. "
"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) -> None:
super().__init__(topic=topic, service=service)
def __init__(self, *, topic: str, service: ChatCompletionClientBase, max_rounds: int | None = None) -> None:
super().__init__(topic=topic, service=service, max_rounds=max_rounds)
self._round_robin_index = 0
async def _render_prompt(self, template: str, **kwargs: Any) -> str:
@@ -20,7 +20,7 @@ from agent_framework import (
WorkflowEvent,
)
from agent_framework.azure import AzureOpenAIChatClient
from agent_framework.orchestrations import HandoffBuilder, HandoffUserInputRequest
from agent_framework.orchestrations import HandoffAgentUserRequest, HandoffBuilder
from azure.identity import AzureCliCredential
from semantic_kernel.agents import Agent, ChatCompletionAgent, HandoffOrchestration, OrchestrationHandoffs
from semantic_kernel.agents.runtime import InProcessRuntime
@@ -223,7 +223,7 @@ async def _drain_events(stream: AsyncIterable[WorkflowEvent]) -> list[WorkflowEv
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, HandoffUserInputRequest):
if event.type == "request_info" and isinstance(event.data, HandoffAgentUserRequest):
requests.append(event)
return requests
@@ -241,12 +241,16 @@ async def run_agent_framework_example(initial_task: str, scripted_responses: Seq
triage, refund, status, returns = _create_af_agents(client)
workflow = (
HandoffBuilder(name="sk_af_handoff_migration", participants=[triage, refund, status, returns])
.set_coordinator(triage)
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)
.add_handoff(returns, [triage])
.build()
)
@@ -260,7 +264,7 @@ async def run_agent_framework_example(initial_task: str, scripted_responses: Seq
user_reply = next(scripted_iter)
except StopIteration:
user_reply = "Thanks, that's all."
responses = {request.request_id: user_reply for request in pending}
responses = {request.request_id: [Message(role="user", text=user_reply)] for request in pending}
final_events = await _drain_events(workflow.run(stream=True, responses=responses))
pending = _collect_handoff_requests(final_events)
@@ -19,7 +19,6 @@ from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient, OpenAIResponsesClient
from agent_framework.orchestrations import MagenticBuilder
from semantic_kernel.agents import (
Agent,
ChatCompletionAgent,
MagenticOrchestration,
OpenAIAssistantAgent,
@@ -44,7 +43,7 @@ PROMPT = (
######################################################################
async def build_semantic_kernel_agents() -> list[Agent]:
async def build_semantic_kernel_agents() -> list:
research_agent = ChatCompletionAgent(
name="ResearchAgent",
description="A helpful assistant with access to web search. Ask it to perform web searches.",
@@ -135,19 +134,19 @@ async def run_agent_framework_example(prompt: str) -> str | None:
instructions=(
"You are a Researcher. You find information without additional computation or quantitative analysis."
),
client=OpenAIChatClient(ai_model_id="gpt-4o-search-preview"),
client=OpenAIChatClient(model_id="gpt-4o-search-preview"),
)
# Create code interpreter tool using instance method
# Create code interpreter tool using static method
coder_client = OpenAIResponsesClient()
code_interpreter_tool = coder_client.get_code_interpreter_tool()
code_interpreter_tool = OpenAIResponsesClient.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,
tools=[code_interpreter_tool],
)
# Create a manager agent for orchestration
@@ -158,12 +157,22 @@ async def run_agent_framework_example(prompt: str) -> str | None:
client=OpenAIChatClient(),
)
workflow = MagenticBuilder(participants=[researcher, coder], manager_agent=manager_agent).build()
workflow = MagenticBuilder(
participants=[researcher, coder], manager_agent=manager_agent
).build()
final_text: str | None = None
async for event in workflow.run(prompt, stream=True):
if event.type == "output":
final_text = cast(str, event.data)
data = event.data
if isinstance(data, str):
final_text = data
elif isinstance(data, list):
# Extract text from the last assistant message
for msg in reversed(data):
if hasattr(msg, "text") and msg.text:
final_text = msg.text
break
return final_text
@@ -153,7 +153,7 @@ async def run_semantic_kernel_process_example() -> None:
kernel=kernel,
initial_event=KernelProcessEvent(id=CommonEvents.START_PROCESS.value, data="Initial"),
) as process_context:
process_state = await process_context.get_executor_state()
process_state = await process_context.get_state()
c_step_state: KernelProcessStepState[CStepState] | None = next(
(s.state for s in process_state.steps if s.state.name == "CStep"),
None,
@@ -144,7 +144,7 @@ async def run_semantic_kernel_nested_process() -> None:
initial_event=ProcessEvents.START_PROCESS.value,
data="Test",
)
process_info = await process_handle.get_executor_state()
process_info = await process_handle.get_state()
inner_process: KernelProcess | None = next(
(s for s in process_info.steps if s.state.name == "Inner"),