n4nAI

Migrating from AutoGen to Microsoft Agent Framework

Step-by-step guide to migrate AutoGen to Microsoft Agent Framework: inventory, agent mapping, tool porting, orchestration, and verification with code.

n4n Team4 min read820 words

Audio narration

Coming soon — every post will get a voice note here.

When you migrate AutoGen to Microsoft Agent Framework, you trade a flexible research library for a structured runtime built for production tracing, deployment, and governance. The mental model stays similar—agents, tools, and orchestration—but the code-level primitives and lifecycle management change. This guide gives you an end-to-end path to move a working AutoGen pipeline without rewriting your business logic.

Step 1: Inventory your AutoGen surface area

Before changing any code, map what you actually use. Most AutoGen apps rely on a small set of primitives: AssistantAgent, UserProxyAgent, GroupChat, and a config_list for model access. Custom functions registered via register_function or the functions parameter are the real IP, and they are what you must protect during the move.

# autogen_inventory.py (before)
from autogen import AssistantAgent, UserProxyAgent, config_list_from_json

config_list = config_list_from_json("oai_config.json")
assistant = AssistantAgent("assistant", llm_config={"config_list": config_list})
user = UserProxyAgent("user", human_input_mode="NEVER", max_consecutive_auto_reply=10)

Run a static scan to find all agent constructions and function registrations:

grep -rn "AssistantAgent\|UserProxyAgent\|register_function\|GroupChat" ./src

Success criterion: you have a spreadsheet (or Markdown table) listing each agent, its system message, its tools, its termination conditions, and the human-input mode. Without this map, the later steps become guesswork. Pay special attention to max_consecutive_auto_reply and silent flags—those control flow in AutoGen and have no 1:1 property in the new runtime.

Step 2: Stand up Microsoft Agent Framework and a model endpoint

Install the preview SDK. The framework decouples model access from agent logic, so you can keep the same underlying models by pointing both old and new code at an OpenAI-compatible gateway. For example, n4n.ai exposes one OpenAI-compatible endpoint covering 240+ models with automatic fallback when a provider is degraded—handy during a cutover when you don’t want to juggle keys or suffer outages mid-migration.

pip install microsoft-agentframework openai
# model_client.py
from openai import OpenAI

# Works for AutoGen and Microsoft Agent Framework alike
client = OpenAI(
    base_url="https://api.n4n.ai/v1",
    api_key="YOUR_KEY",
)

Set environment variables so the framework picks up the endpoint without code changes later:

export AZURE_AI_AGENT_ENDPOINT="https://api.n4n.ai/v1"
export AZURE_AI_AGENT_KEY="YOUR_KEY"

Verification: python -c "import microsoft_agentframework; print('ok')" exits 0, and a minimal completion call returns tokens. Run a quick smoke test against the gateway to confirm the model string you plan to use is supported.

Step 3: Replace agent constructors with framework agents

AutoGen’s AssistantAgent bundles system prompt, model config, and reply logic. In Microsoft Agent Framework, an agent is a named unit with instructions and a bound toolset; the runtime owns the conversation loop. This separation is the single biggest conceptual shift when you migrate AutoGen to Microsoft Agent Framework.

A typical AutoGen assistant:

assistant = AssistantAgent(
    "coder",
    system_message="You write Python. Reply with code only.",
    llm_config={"config_list": config_list},
)

The migration equivalent separates concerns. You declare the agent and register it with a runtime:

# agent_framework_agents.py
from microsoft.agentframework import Agent, AgentRuntime

runtime = AgentRuntime(endpoint="https://api.n4n.ai/v1", api_key="YOUR_KEY")

coder = Agent(
    name="coder",
    instructions="You write Python. Reply with code only.",
    model="gpt-4o-mini",
)
runtime.register_agent(coder)

If you used UserProxyAgent to inject human approval, replace it with a runtime hook that blocks on input. In AutoGen the proxy agent is a first-class participant; in the new framework, human interaction is a cross-cutting concern.

# AutoGen
user = UserProxyAgent("user", human_input_mode="ALWAYS")

# Agent Framework
async def human_approval(turn):
    if turn.requires_approval:
        return input("Approve? (y/n): ")
    return None

runtime.set_human_hook(human_approval)

The exact hook signature depends on your framework version; check the preview docs for RuntimeHooks. The pattern—externalizing human interaction from agent objects—is the key shift. Do not try to emulate UserProxyAgent as a regular agent; you will fight the runtime.

Step 4: Port tools and functions

AutoGen binds Python functions to agents via register_function or the functions list. Microsoft Agent Framework expects tools as typed callables with docstrings and Pydantic schemas. The function body stays identical; only the registration wrapper changes.

AutoGen tool:

def get_weather(city: str):
    """Return weather for a city."""
    return f"Sunny in {city}"

assistant.register_function("get_weather", get_weather)

Framework tool:

from pydantic import BaseModel

class WeatherArgs(BaseModel):
    city: str

@runtime.tool
def get_weather(args: WeatherArgs) -> str:
    """Return weather for a city."""
    return f"Sunny in {args.city}"

If you have ten tools, write a small adapter that iterates over your AutoGen function registry, extracts the signature, and re-registers them with the new decorator. Verification: call runtime.list_tools() and confirm each original function name appears with the correct schema. Missing schema fields are the most common cause of silent tool-call failures after migration.

Step 5: Rebuild orchestration and group chats

AutoGen’s GroupChat with a GroupChatManager is the hardest part to migrate because the new framework favors explicit orchestrator patterns (supervisor, sequential, or custom graph). Map your group chat roles to a supervisor agent that delegates.

AutoGen group chat:

from autogen import GroupChat, GroupChatManager
group = GroupChat(agents=[assistant, critic], messages=[], max_round=5)
manager = GroupChatManager(group, llm_config={"config_list": config_list})

Agent Framework supervisor:

supervisor = Agent(
    name="supervisor",
    instructions="Delegate coding to 'coder' and review to 'critic'.",
    model="gpt-4o",
)
runtime.set_orchestrator("supervisor")

For cyclic or conditional flows, define a custom orchestrator function that receives the message history and returns the next agent name. This is more code than GroupChat but gives you deterministic control and logging. When you migrate AutoGen to Microsoft Agent Framework, budget most of your effort here—the agent swaps are trivial, the conversation topology is not.

Step 6: Migrate tests and verify end-to-end

Your AutoGen tests likely assert on message content or function call counts. Rewrite them against the runtime’s turn API. Keep the old suite running in parallel.

Example pytest snippet:

async def test_migration():
    runtime = AgentRuntime(endpoint="https://api.n4n.ai/v1", api_key="test")
    runtime.register_agent(coder)
    result = await runtime.run("Write a hello world function")
    assert "def" in result.messages[-1].content

Run the original AutoGen suite alongside the new suite in CI. Success looks like: identical tool outputs for the same input prompt, and latency within 20% of the old path. Add a differential test that feeds a fixed scenario to both systems and compares the final tool calls, not the exact natural language, since model responses will vary.

Step 7: Cutover and cleanup

Flip your entrypoint to import the new runtime. Delete autogen from requirements once traffic confirms stability. Keep the config_list JSON as a reference but move all model routing to the gateway or framework endpoint. If you used the OpenAI-compatible gateway, per-token usage metering should match your expected counts without extra instrumentation.

Final verification: production trace shows agent spans, tool calls, and human hooks logged. The migration is mechanical for agents, semantic for orchestration—plan the second part first, and the cutover will be a non-event.

Tagsautogenmicrosoft-agent-frameworkmigration

Written by

n4n Team

The team building n4n — a single OpenAI-compatible API in front of 240+ models, with automatic fallback, load balancing and pay-per-token metering.

More from n4n Team →

All autogen & microsoft agent framework posts →