Microsoft Agent Framework Basics
9 examples to get you started with Microsoft Agent Framework - 6 basic and 3 intermediate.
These sketches follow the Python 1.0 surface (agent-framework).
Verify client constructors, model names, and orchestration imports at build against current Microsoft Learn samples.
Prerequisites
- Python 3.10+ and
pip install agent-framework(verify extras for your provider). - Credentials for at least one chat provider (OpenAI API key, Azure CLI/
az loginfor Foundry, or equivalent). - Comfort with async Python (
asyncio.run). - Optional context: From AutoGen and Semantic Kernel to Microsoft Agent Framework 1.0.
Basic Examples
1. Install and Create One Agent
Start with a single agent before multi-agent wiring.
# pip install agent-framework
import asyncio
from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient
async def main():
client = OpenAIChatClient(model="gpt-4o") # model id: verify at build
agent = client.as_agent(
name="HelloAgent",
instructions="You are a friendly assistant. Keep answers brief.",
)
result = await agent.run("Name one benefit of multi-agent systems.")
print(result.text)
asyncio.run(main())as_agentis the common factory from a chat client.- Agents are multi-turn on tools by default; keep instructions short for demos.
- Without a session, each
runis independent.
Related: From AutoGen and Semantic Kernel to Microsoft Agent Framework 1.0 - product context
2. Continue a Conversation with a Session
Pass an AgentSession when later turns must see earlier turns.
async def chat_with_memory(agent):
session = agent.create_session()
r1 = await agent.run("Remember the codeword is azure-lark.", session=session)
r2 = await agent.run("What is the codeword?", session=session)
print(r1.text, r2.text)- Sessions hold conversation state; agents alone do not invent durable history.
- Use one session per user thread in a product, not a global shared session.
- Provider-backed sessions may differ from local sessions - verify for your client.
Related: Conversational Multi-Agent Patterns: Agent-to-Agent Chat - multi-party chat
3. Attach a Function Tool
Tools are plain functions (optionally @tool) passed into the agent.
from agent_framework import tool
from typing import Annotated
@tool
def word_count(text: Annotated[str, "Text to measure"]) -> str:
"""Count words in text."""
return str(len(text.split()))
agent = client.as_agent(
name="Counter",
instructions="Use word_count when the user asks for a count.",
tools=[word_count],
)
print((await agent.run("How many words are in: multi agent systems rock?")).text)- Docstrings and annotations become tool schema for the model.
- Prefer few high-quality tools over a kitchen-sink registry.
- Hosted tools (code interpreter, web search) depend on provider support - verify at build.
Related: Enterprise Plugins and Connectors from Semantic Kernel - enterprise tool wiring
4. Define Two Specialist Agents
Separate roles with instructions and names before you orchestrate them.
writer = client.as_agent(
name="writer",
instructions="You are a concise copywriter. Output one punchy marketing sentence.",
)
reviewer = client.as_agent(
name="reviewer",
instructions="You are a reviewer. Give brief feedback on the previous message only.",
)- Names matter for logs and conversation traces.
- Specialists should own different goals, not identical prompts.
- Keep tools least-privilege per specialist when you add them.
Related: Conversational Multi-Agent Patterns: Agent-to-Agent Chat - chat patterns
5. Sequential Two-Agent Handoff (Core Demo)
Run writer then reviewer with a sequential orchestration builder.
from typing import cast
from agent_framework import Message
from agent_framework.orchestrations import SequentialBuilder
async def two_agent_handoff(client):
writer = client.as_agent(
name="writer",
instructions="Write one punchy product tagline. No preamble.",
)
reviewer = client.as_agent(
name="reviewer",
instructions="Critique the tagline in two short bullets.",
)
workflow = SequentialBuilder(participants=[writer, reviewer]).build()
task = "Tagline for an enterprise multi-agent SDK."
async for event in workflow.run(task, stream=True):
if event.type == "output":
history = cast(list[Message], event.data)
for msg in history:
print(f"[{msg.author_name or msg.role}]: {msg.text}")- Sequential orchestration is the simplest agent-to-agent handoff shape.
- Each participant appends to a shared conversation stream.
- Stream events let you observe intermediate outputs, not only the final string.
Related: Graph-Based Workflows in Microsoft Agent Framework - when you need typed graphs
6. Foundry Client Variant
Same agent idea with Microsoft Foundry authentication.
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential
client = FoundryChatClient(
project_endpoint="https://YOUR_PROJECT.services.ai.azure.com/api/projects/YOUR_PROJECT",
model="gpt-4o", # deployment / model: verify at build
credential=AzureCliCredential(),
)
agent = client.as_agent(name="FoundryHello", instructions="Be brief.")- Prefer specific production credentials over broad default chains when you leave the laptop.
- Project endpoint and model deployment names are environment-specific.
- Foundry unlocks hosted tools and managed options beyond local demos.
Related: Governance and Enterprise Controls in Microsoft Agent Framework - enterprise controls
Intermediate Examples
7. Agent-as-a-Tool Composition
Wrap a specialist with .as_tool() so a coordinator can call it.
researcher = client.as_agent(
name="researcher",
instructions="Answer with three bullet facts only.",
)
research_tool = researcher.as_tool(
name="research_bullets",
description="Produce three factual bullets on a topic",
arg_name="topic",
arg_description="Topic to research",
)
coordinator = client.as_agent(
name="coordinator",
instructions="Use research_bullets, then write a one-sentence summary.",
tools=[research_tool],
)
print((await coordinator.run("Benefits of checkpointed workflows")).text)- Agent-as-tool builds hierarchy without a full graph.
- Inner agents stay narrow; the outer agent owns user conversation.
- Avoid deep nesting until you can log each hop.
Related: Conversational Multi-Agent Patterns: Agent-to-Agent Chat - collaboration shapes
8. Minimal Middleware Hook
Intercept runs for logging without changing instructions.
from agent_framework import AgentContext
from collections.abc import Awaitable, Callable
async def log_runs(context: AgentContext, call_next: Callable[[], Awaitable[None]]) -> None:
print("start", context.agent.name if context.agent else "agent")
await call_next()
print("done")
agent = client.as_agent(
name="Logged",
instructions="Reply in one sentence.",
middleware=[log_runs],
)- Middleware is the enterprise extension point for policy and telemetry.
- Agent, function, and chat middleware form chains - order matters.
- Prefer middleware for security checks over stuffing rules into the prompt alone.
Related: Governance and Enterprise Controls in Microsoft Agent Framework - deeper controls
9. When to Graduate from Sequential Chat to a Graph
Sequential multi-agent chat is enough until process control requires more.
# Decision sketch (not framework API)
def choose_shape(task: str) -> str:
if task in {"tagline_review", "draft_then_edit"}:
return "sequential_orchestration"
if task in {"fan_out_research", "approval_gate", "checkpointed_etl"}:
return "workflow_graph"
return "single_agent"- Use sequential chat for open collaboration and critique loops.
- Use graph workflows for typed edges, joins, approvals, and resume.
- Do not invent a third agent until roles or privileges truly diverge.
Related: Graph-Based Workflows in Microsoft Agent Framework - graph model Related: Microsoft Agent Framework Best Practices - production checklist
Related
- From AutoGen and Semantic Kernel to Microsoft Agent Framework 1.0 - merger story
- Conversational Multi-Agent Patterns: Agent-to-Agent Chat - chat recipes
- Graph-Based Workflows in Microsoft Agent Framework - workflows
- Migrating an Existing AutoGen Project to Microsoft Agent Framework - migration
- Microsoft Agent Framework Best Practices - practices list
Stack versions: Pins from the category manifest (verify at build): OpenRouter (~315+ models, July 2026 pricing/fees); LangGraph 1.0+; CrewAI 1.14+; Microsoft Agent Framework 1.0; Vercel AI SDK 6; Pydantic AI (latest); LlamaIndex (latest); OpenAI Agents SDK (latest + MCP); MCP (Linux Foundation governance); A2A (HTTP+SSE+JSON-RPC 2.0); Solana
@solana/web3.js+@solana/spl-token.