GeekCoding101 make your way to geek

Microsoft Agent Framework in Python: First Agent With a Tool

Microsoft Agent Framework explained: how it relates to Semantic Kernel and AutoGen, which pip package to install, and a Python agent that calls a tool.

8 min read
Terminal screenshot of installing agent-framework-openai with uv and listing the installed agent-framework package versions
On this pageWhat is Microsoft Agent Framework?

Microsoft Agent Framework is Microsoft’s open-source framework for building AI agents and multi-agent workflows in .NET, Python and Go (Go is in public preview). In Python you install it with pip (or uv), define a tool as a plain function with the @tool decorator, and pass it to an Agent.

According to Microsoft’s overview, it is the direct successor to Semantic Kernel and AutoGen, built by the same teams, and both have migration guides. This guide covers what it is, which package to install, and a first Microsoft Agent Framework Python agent with a function tool, so you can see exactly how the tool-call loop works. If you want the concept first, read What Is an AI Agent and How to Build One.

What is Microsoft Agent Framework?

It gives you three things: an agent object that wraps a model client, a way to expose your own functions to the model as tools, and workflows that connect several agents. The same ideas exist across the .NET, Python and Go versions.

If you have used Semantic Kernel or AutoGen, think of Agent Framework as the place where both lines of work continue. You don’t need either of them to follow this guide.

Which pip package do you need?

As of the facts checked on 2026-12-03:

  • agent-framework is the meta package. Version 1.26.0 was released on 2026-11-12 and needs Python 3.11 or newer.
  • agent-framework-openai (version 1.18.2) provides the OpenAI clients: OpenAIChatClient, which uses the Responses API, and OpenAIChatCompletionClient, which uses the Chat Completions API.

For this guide, agent-framework-openai is enough. The Chat Completions client is useful because many local and third-party servers speak that format.

What this example does (and does not) prove

The example below runs without any API key or model. It talks to a tiny stand-in server that speaks the Chat Completions format and returns a scripted tool call. That proves the framework’s tool loop and lets you read the exact requests it sends. It does not show model quality: no real model was run for this article.

The stand-in server is about 35 lines of http.server on 127.0.0.1:8089. When the last message in a request does not have the role tool (the first request in this run), it replies with a tool call for disk_usage with the path /. When the last message does have the role tool, it answers with that result as text. For every request it prints the last role and the tool names, and for the second kind it also prints the tool result.

Set up the environment

Terminal window
uv venv
source .venv/bin/activate
uv pip install agent-framework-openai
uv pip list | grep agent-framework
Terminal output: uv venv, installing agent-framework-openai, and uv pip list showing agent-framework-core 1.26.0 and agent-framework-openai 1.18.2

This run used Python 3.12.12 and installed agent-framework-core 1.26.0 and agent-framework-openai 1.18.2. Your versions may be newer.

The stand-in model server

Save this as fake_model.py:

"""A tiny stand-in for a Chat Completions endpoint. It is NOT a model:
turn 1 always asks for the disk_usage tool, turn 2 repeats the tool result."""
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
last = body["messages"][-1]
tools = [t["function"]["name"] for t in body.get("tools", [])]
print(f"request: last role={last['role']} tools={tools}", flush=True)
if last["role"] == "tool":
print(f" tool result received: {last['content']}", flush=True)
message = {"role": "assistant", "content": f"The tool says: {last['content']}"}
reason = "stop"
else:
call = {"id": "call_1", "type": "function",
"function": {"name": "disk_usage", "arguments": '{"path": "/"}'}}
message = {"role": "assistant", "content": None, "tool_calls": [call]}
reason = "tool_calls"
reply = {"id": "x", "object": "chat.completion", "created": 0, "model": body["model"],
"choices": [{"index": 0, "message": message, "finish_reason": reason}]}
data = json.dumps(reply).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def log_message(self, *args):
pass
HTTPServer(("127.0.0.1", 8089), Handler).serve_forever()

The agent with a function tool

Save this as agent.py:

import asyncio
import os
import shutil
from typing import Annotated
from agent_framework import Agent, tool
from agent_framework.openai import OpenAIChatCompletionClient
from pydantic import Field
@tool(approval_mode="never_require")
def disk_usage(path: Annotated[str, Field(description="Directory to check")]) -> str:
"""Report how full the disk that holds a directory is."""
total, used, _free = shutil.disk_usage(path)
return f"{path} is {used / total:.0%} full"
async def main() -> None:
client = OpenAIChatCompletionClient(
model=os.getenv("MODEL", "fake-model"),
base_url=os.getenv("BASE_URL", "http://127.0.0.1:8089/v1"),
api_key=os.getenv("API_KEY", "not-needed"),
)
agent = Agent(
client=client,
name="ops",
instructions="Answer using the tools.",
tools=[disk_usage],
)
result = await agent.run("How full is the root disk?")
print(result.text)
for message in result.messages:
print(message.role, [content.type for content in message.contents])
asyncio.run(main())

Three parts of it matter.

Defining a tool with @tool

disk_usage is an ordinary Python function using shutil.disk_usage, decorated with @tool(approval_mode="never_require"). That setting means the agent runs it without asking for approval, which is fine for a read-only demo and worth reconsidering for anything that changes state.

According to the function tools documentation, if you omit name and description, the framework uses the function name and its docstring. Parameters are described with Annotated plus a pydantic Field(description=...), which is what the script does for path. The model sees those descriptions, so write them for the model.

Building the client and agent

OpenAIChatCompletionClient takes a model name, a base URL and an API key. The script reads them from MODEL, BASE_URL and API_KEY, with defaults that point at the stand-in server. Then Agent(client=client, name="ops", instructions="Answer using the tools.", tools=[disk_usage]) ties it together, and await agent.run("How full is the root disk?") runs one turn.

Reading the result

The script prints result.text, then loops over result.messages and prints each message’s role and content types. That loop is what makes the tool call visible.

Run it

Start the stand-in server in the background, then run the agent and read the server log:

Terminal window
python fake_model.py > server.log 2>&1 &
python agent.py
cat server.log
Terminal output: agent.py prints the tool result, then function_call, function_result and text messages, and server.log shows two requests

How the tool-call loop works on the wire

In this run the tool reported that / was 96% full; your number will reflect your own disk. The server saw two requests:

  1. First request, last role user. The agent sends your question plus the tool’s name and parameter schema. The stand-in replies with a tool_calls message asking for disk_usage with path set to /.
  2. Second request, last role tool. The framework runs your Python function itself, appends the result as a tool message, and calls the model again. This time the stand-in replies with plain text.

That is why the message list reads assistant (function call), tool (function result), assistant (text). Your code made one agent.run call; the framework handled the round trip.

Because a real model generates those tool calls, treat their arguments as untrusted input. The documentation says so explicitly: validate paths, limits and anything else the model can influence before acting on it.

The loop can also be bounded. The docs describe max_iterations and max_function_calls on client.function_invocation_configuration, which stop a model that keeps calling tools. In agent-framework-core 1.26.0 the defaults are 40 for max_iterations and None for max_function_calls. See the function tools page for the exact usage.

Point it at a real provider

Nothing in agent.py is specific to the stand-in server. To use a real endpoint, set the three environment variables:

Terminal window
export MODEL="your-model-name"
export BASE_URL="https://your-provider.example/v1"
export API_KEY="your-key"
python agent.py

With a real model, the model decides whether to call disk_usage at all, so behaviour will vary with the model and the prompt. The OpenAI provider docs also list OPENAI_API_KEY and OPENAI_BASE_URL as environment variables. Note that the framework does not load .env files by itself, so export the variables in your shell or load the file in your own code.

For a local model, Ollama’s OpenAI-compatible endpoint is http://localhost:11434/v1/. Set BASE_URL to that and MODEL to a model you have pulled that supports tool calling.

Multi-turn sessions and streaming

The two snippets below are taken from the documentation pattern and were not run for this article.

A session keeps conversation history across calls:

session = agent.create_session()
first = await agent.run("How full is the root disk?", session=session)
second = await agent.run("And is that a lot?", session=session)

Streaming returns chunks as they arrive:

async for chunk in agent.run("How full is the root disk?", stream=True):
print(chunk.text, end="", flush=True)

Troubleshooting

  • Connection refused when running agent.py. The stand-in server is not running, or it is not on 127.0.0.1:8089. Start fake_model.py first and check server.log.
  • Wrong endpoint format. OpenAIChatCompletionClient speaks Chat Completions, while OpenAIChatClient uses the Responses API. If your server only implements one of them, pick the matching client.
  • The tool is never called with a real model. The model chooses. Check that the tool description is clear and that the model supports tool calling.

If you are comparing ways to give a model access to tools, MCP vs API and What Is an MCP Server cover the other common route, and A Quick Guide is a good companion read.

FAQ

What is Microsoft Agent Framework?

It is Microsoft’s open-source framework for building agents and multi-agent workflows in .NET, Python and Go. It is described as the direct successor to Semantic Kernel and AutoGen.

Is Microsoft Agent Framework the same as Semantic Kernel or AutoGen?

No, but it comes from the same teams and replaces both as the direction going forward. Microsoft publishes migration guides for each, linked from the overview page.

Which Python version and package do I need?

The agent-framework meta package needs Python 3.11 or newer. For OpenAI-style endpoints, install agent-framework-openai, as shown above.

Do I need an API key to try it?

Not for this guide. The example uses a local stand-in server, so no key or model is needed. For real use, set MODEL, BASE_URL and API_KEY.

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.

Keep reading

All posts