Velamuvi AIAcademy

Lesson 37 of 39 · Production

Migrating From AutoGen and Semantic Kernel

Move AutoGen and Semantic Kernel code to Microsoft Agent Framework: name maps, agents, tools, teams, threads and filters, side by side with tested code.

  • 10 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain why AutoGen and Semantic Kernel projects move to Agent Framework
  • Map AutoGen and Semantic Kernel names to their Agent Framework equivalents
  • Rewrite an AutoGen agent and an AutoGen team with Agent, tool and GroupChatBuilder
  • Rewrite a Semantic Kernel agent, plugin and thread with Agent, tool and AgentSession
  • Plan a step-by-step migration that keeps your app working

Why move, and what stays the same

Agent Framework is the successor to both AutoGen and Semantic Kernel, built by the same teams. AutoGen's repository is archived and now points to Agent Framework, and Microsoft publishes migration guides from both. The good news: the ideas carry over. Agents, tools, conversations, teams and workflows all exist on both sides; mostly the names and the calls change.

A migration map is just data, so you can even apply it with code:

Try it yourselfPython
# A migration cheat sheet as data: old names on the left, Agent Framework on the right.
AUTOGEN = {
    "AssistantAgent": "Agent",
    "model_client=": "client=",
    "system_message=": "instructions=",
    "agent.run(task=": "agent.run(",
    "RoundRobinGroupChat": "GroupChatBuilder",
    "Swarm": "HandoffBuilder",
    "MagenticOneGroupChat": "MagenticBuilder",
    "GraphFlow": "WorkflowBuilder",
}
SEMANTIC_KERNEL = {
    "ChatCompletionAgent": "Agent",
    "service=": "client=",
    "ChatHistoryAgentThread": "AgentSession",
    "agent.get_response(messages=": "agent.run(",
}


def translate(line, table):
    for old, new in table.items():
        line = line.replace(old, new)
    return line


print(translate("agent = AssistantAgent(model_client=client, system_message=prompt)", AUTOGEN))
print(translate("result = await agent.run(task=question)", AUTOGEN))
print(translate("reply = await agent.get_response(messages=question, thread=thread)", SEMANTIC_KERNEL))

Real code needs a bit more than search and replace, as the last line shows: thread= becomes session=. The sections below go through each piece.

The migration map

AutoGenSemantic KernelAgent Framework
AssistantAgentChatCompletionAgentAgent
model_client=OpenAIChatCompletionClient(...)service=OpenAIChatCompletion(...)client=OpenAIChatClient(...)
system_message=instructions=instructions=
plain functions in tools=@kernel_function methods in a plugin@tool functions (or plain functions) in tools=
await agent.run(task=...)await agent.get_response(messages=...)await agent.run(...)
result.messages[-1].contentresponse.contentresponse.text
model_contextChatHistoryAgentThreadAgentSession with history providers
RoundRobinGroupChat, SelectorGroupChatGroupChatOrchestration, AgentGroupChatGroupChatBuilder
SwarmHandoffOrchestrationHandoffBuilder
MagenticOneGroupChatMagenticOrchestrationMagenticBuilder
GraphFlowProcess framework (ProcessBuilder)WorkflowBuilder
filtersmiddleware

The examples below were run with AutoGen 0.7 and Semantic Kernel 1.47, so the "before" code is real code from those versions.

From AutoGen: one agent with a tool

Before, in AutoGen:

import asyncio

from autogen_agentchat.agents import AssistantAgent
from autogen_ext.models.openai import OpenAIChatCompletionClient


def bike_price(model: str) -> str:
    """Daily rental price of one Velo bike model."""
    return {"City E": "35 EUR a day", "Trail X": "50 EUR a day"}[model]


async def main():
    agent = AssistantAgent(
        name="velo_desk",
        model_client=OpenAIChatCompletionClient(model="MODEL_NAME"),
        system_message="You are Velo's rental desk in Porto.",
        tools=[bike_price],
        reflect_on_tool_use=True,
    )
    result = await agent.run(task="How much does a City E cost?")
    print(result.messages[-1].content)


asyncio.run(main())

After, in Agent Framework:

import asyncio

from agent_framework import Agent, tool
from agent_framework.openai import OpenAIChatClient


@tool
def bike_price(model: str) -> str:
    """Daily rental price of one Velo bike model."""
    return {"City E": "35 EUR a day", "Trail X": "50 EUR a day"}[model]


async def main():
    agent = Agent(
        name="velo_desk",
        client=OpenAIChatClient(model="MODEL_NAME"),
        instructions="You are Velo's rental desk in Porto.",
        tools=[bike_price],
    )
    response = await agent.run("How much does a City E cost?")
    print(response.text)


asyncio.run(main())
Output
A City E costs 35 EUR a day.

The changes: AssistantAgent becomes Agent, model_client becomes client, system_message becomes instructions, and the function gets the @tool decorator (a plain function works too, but @tool lets you set names, approvals and more). run() takes the text directly and returns an AgentResponse with .text. There's no reflect_on_tool_use: an Agent Framework agent always calls the model again with the tool's result and answers in words.

From AutoGen: a team

AutoGen's RoundRobinGroupChat with a termination condition:

import asyncio

from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.conditions import MaxMessageTermination, TextMentionTermination
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_ext.models.openai import OpenAIChatCompletionClient


async def main():
    client = OpenAIChatCompletionClient(model="MODEL_NAME")
    writer = AssistantAgent("writer", model_client=client,
                            system_message="Write one slogan. Use the reviewer's feedback if there is any.")
    reviewer = AssistantAgent("reviewer", model_client=client,
                              system_message="Review the latest slogan. Reply APPROVED if it is short, clear and "
                                             "names the price; otherwise say what to change.")
    team = RoundRobinGroupChat(
        [writer, reviewer],
        termination_condition=TextMentionTermination("APPROVED") | MaxMessageTermination(6),
    )
    result = await team.run(task="A slogan for the Velo City E, our rental e-bike at 35 EUR a day")
    for message in result.messages[1:]:
        print(f"{message.source}: {message.content}")


asyncio.run(main())

The same team with GroupChatBuilder, using the selection function and termination condition from the group chat lesson:

import asyncio

from agent_framework import Agent, Message
from agent_framework.openai import OpenAIChatClient
from agent_framework.orchestrations import GroupChatBuilder, GroupChatState


def next_speaker(state: GroupChatState) -> str:            # the selection function
    return "writer" if state.current_round % 2 == 0 else "reviewer"


def approved(conversation: list[Message]) -> bool:         # the termination condition
    return any(m.author_name == "reviewer" and m.text.startswith("APPROVED") for m in conversation)


async def main():
    client = OpenAIChatClient(model="MODEL_NAME")
    writer = Agent(client=client, name="writer", description="Writes slogans",
                   instructions="Write one slogan. Use the reviewer's feedback if there is any.")
    reviewer = Agent(client=client, name="reviewer", description="Checks slogans",
                     instructions="Review the latest slogan. Reply APPROVED if it is short, clear and "
                                  "names the price; otherwise say what to change.")
    workflow = GroupChatBuilder(
        participants=[writer, reviewer],
        selection_func=next_speaker,
        termination_condition=approved,
        max_rounds=6,                                       # a safety net
        intermediate_output_from="all",                     # show every reply as it happens
    ).build()

    result = await workflow.run("A slogan for the Velo City E, our rental e-bike at 35 EUR a day")
    for reply in result.get_intermediate_outputs():
        print(f"{reply.messages[-1].author_name}: {reply.text}")
    print(result.get_outputs()[0].text)


asyncio.run(main())
Output
writer: Pedal further, worry less.
reviewer: Too vague. Please mention the 35 EUR price.
writer: Ride all day for 35 EUR.
reviewer: APPROVED: short, clear and it names the price.
The group chat has reached its termination condition.

The round-robin order becomes a small selection function, and TextMentionTermination("APPROVED") becomes a function that checks the conversation. max_rounds plays the role of MaxMessageTermination as a safety net. For SelectorGroupChat, where a model picks the next speaker, pass orchestrator_agent= instead of selection_func=; for Swarm, use HandoffBuilder; for GraphFlow, build the graph with WorkflowBuilder, as in the workflow lessons.

From Semantic Kernel: agent, plugin and thread

Before, in Semantic Kernel, with a plugin class and a thread for the conversation:

import asyncio

from semantic_kernel.agents import ChatCompletionAgent, ChatHistoryAgentThread
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.functions import kernel_function


class VeloPlugin:
    @kernel_function(description="Daily rental price of one Velo bike model.")
    def bike_price(self, model: str) -> str:
        return {"City E": "35 EUR a day", "Trail X": "50 EUR a day"}[model]


async def main():
    agent = ChatCompletionAgent(
        service=OpenAIChatCompletion(ai_model_id="MODEL_NAME"),
        name="velo_desk",
        instructions="You are Velo's rental desk in Porto.",
        plugins=[VeloPlugin()],
    )
    thread = ChatHistoryAgentThread()
    response = await agent.get_response(messages="How much does a City E cost?", thread=thread)
    print(response.content)
    response = await agent.get_response(messages="And for two days?", thread=response.thread)
    print(response.content)


asyncio.run(main())

After, in Agent Framework:

import asyncio

from agent_framework import Agent, tool
from agent_framework.openai import OpenAIChatClient


@tool
def bike_price(model: str) -> str:
    """Daily rental price of one Velo bike model."""
    return {"City E": "35 EUR a day", "Trail X": "50 EUR a day"}[model]


async def main():
    agent = Agent(
        name="velo_desk",
        client=OpenAIChatClient(model="MODEL_NAME"),
        instructions="You are Velo's rental desk in Porto.",
        tools=[bike_price],
    )
    session = agent.create_session()                      # was: ChatHistoryAgentThread()
    print((await agent.run("How much does a City E cost?", session=session)).text)
    print((await agent.run("And for two days?", session=session)).text)


asyncio.run(main())
Output
A City E costs 35 EUR a day.
Two days with a City E cost 70 EUR.

Plugins become plain @tool functions, with no class or kernel needed. The thread becomes an AgentSession, which you create once and pass to every run instead of taking a new thread from each response. Semantic Kernel's filters become middleware: a function invocation filter is a function middleware, and a filter around the model call is chat middleware. Semantic Kernel's agent orchestrations (SequentialOrchestration, ConcurrentOrchestration, GroupChatOrchestration, HandoffOrchestration, MagenticOrchestration) have direct equivalents in agent_framework.orchestrations, and the Process framework maps to WorkflowBuilder.

A migration plan

  1. Inventory. List every agent, tool, team and workflow, and write down which old classes each one uses.
  2. Tests first. Save real questions and good answers, and turn them into evaluations (see Evaluations and Testing), so you can check that the new version behaves the same.
  3. Leaf agents first. Move single agents and their tools, using the map. Tools are usually the easiest part.
  4. Then conversations and teams. Replace threads with sessions and history providers, and teams with orchestrations or workflows.
  5. Run both side by side. Send some traffic to the new version, compare results and costs with observability, then switch over.

Common mistakes

Practice exercise

Write a small migration helper: turn an AutoGen-style agent configuration into the keyword arguments for an Agent Framework Agent.

Your solutionPython
RENAMES = {"system_message": "instructions"}
DROPPED = {"reflect_on_tool_use"}


def migrate(old):
    # Build a new dictionary: skip the keys in DROPPED,
    # and rename keys found in RENAMES. Keep the original order.
    return old


old = {"name": "velo_desk", "system_message": "You are Velo's rental desk.", "tools": ["bike_price"], "reflect_on_tool_use": True}
print(migrate(old))
print(migrate({"name": "helper", "system_message": "Be brief."}))
Knowledge check

An AutoGen app uses RoundRobinGroupChat with TextMentionTermination. What do you use in Agent Framework?

Summary

  • Agent Framework is the successor to AutoGen and Semantic Kernel; the concepts carry over, the names change.
  • Agents and tools: AssistantAgent / ChatCompletionAgent become Agent, functions and plugins become @tool functions, and run() returns .text.
  • Conversations: threads become AgentSession; Semantic Kernel filters become middleware.
  • Teams and flows: group chats become GroupChatBuilder, swarms HandoffBuilder, Magentic-One MagenticBuilder, graphs and processes WorkflowBuilder.
  • Migrate one piece at a time, with evaluations to prove nothing broke.

Next: Production Checklist.

Finished reading? Tick it off to track your progress.