MAF AcademyLearnCapstoneSandbox
MAF Academy · Microsoft Agent Framework hands-on workshop · labs verified on agent-framework-core 1.26
← All modules
MODULE 3 OF 8 8 minutes

Agent Tools and Function Integration

Give the model hands: typed Python functions it can call, with results fed back into its reasoning.

1.Understanding tools and function calling
2.Creating custom Python functions
3.Registering tools with an AI agent
4.Enabling agents to invoke external functions
5.Processing tool outputs
6.Handling tool execution and responses

On this page

How function calling worksTurn a Python function into a toolTools over your data (pandas)Processing & inspecting tool outputsKey takeawaysHands-on activityQuiz
1Concept

How function calling works

The model never runs your code. It asks to call a function by emitting a structured function call (name + JSON args). MAF executes the Python function, appends the function result to the conversation, and calls the model again — looping until the model answers in text.

UserAgent (MAF)LLMPython tool“Q1 margin for AI Copilot?”messages + tool schemasfunction_call sales_summary(product=…)invoke sales_summary()rows: revenue, cost …function_result appendedfunction_call profit_margin(…)invoke profit_margin()margin=56.1%function_result appendedfinal text answerAgentResponse
Function calling loop: the model requests, MAF executes, results flow back until the model answers.
2Build

Turn a Python function into a tool

Use @tool. MAF builds the JSON schema from type hints, Annotated + Field descriptions and the docstring — so those are your prompt. Write them for the model.

@tool→registers a FunctionTool
def profit_margin(→name → tool name
revenue: Annotated[float, Field(description=…)]→type + description → JSON schema
) -> str:→return text the model can read
"""Calculate profit and margin."""→docstring → tool description
ex3_tools_agent.py
1from typing import Annotated
2from pydantic import Field
3from agent_framework import Agent, tool
4
5@tool
6def profit_margin(
7 revenue: Annotated[float, Field(description="Total revenue")],
8 cost: Annotated[float, Field(description="Total cost")],
9) -> str:
10 """Calculate profit and profit margin percentage."""
11 profit = revenue - cost
12 return f"profit={profit:,.0f}, margin={profit / revenue * 100:.1f}%"
13
14agent = Agent(client=client, instructions="ALWAYS use tools for numbers.",
15 tools=[profit_margin, sales_summary, growth_rate])
3Real data

Tools over your data (pandas)

Tools are the bridge to your systems: databases, CRMs, APIs, files. In the lab, sales_summary filters a pandas DataFrame so the agent answers with real numbers instead of hallucinated ones.

pandas-backed tool
1SALES = pd.read_csv("data/sales.csv")
2
3@tool
4def sales_summary(
5 region: Annotated[str | None, Field(description="North or South; omit for all")] = None,
6 product: Annotated[str | None, Field(description="Cloud Suite or AI Copilot")] = None,
7) -> str:
8 """Return monthly revenue, cost and units from the company sales dataset."""
9 df = SALES
10 if region: df = df[df.region.str.lower() == region.lower()]
11 if product: df = df[df["product"].str.lower() == product.lower()]
12 return df.groupby("month")[["units", "revenue", "cost"]].sum().to_string()
4Results

Processing & inspecting tool outputs

Function calls and results are just content items in response.messages. Inspect them for debugging, auditing or UI ("🔧 called sales_summary").

Handling failures: return a clear "ERROR: …" string instead of raising — the model can read it and recover (ask for valid input, try another tool). For risky actions use @tool(approval_mode="always_require") to require human approval.

inspect the tool loop
1for message in response.messages:
2 for content in message.contents:
3 if content.type == "function_call":
4 print(f"-> call {content.name}({content.arguments})")
5 elif content.type == "function_result":
6 print(f"<- result {content.result}")

Key takeaways

01

The model requests calls; MAF executes them and loops until a text answer.

02

Type hints + Field descriptions + docstrings become the tool schema — write them well.

03

Return readable errors so the model can self-correct.

04

approval_mode='always_require' adds a human gate to risky tools.

Hands-on activity

Build an agent that uses Python functions for business calculations and data retrieval

  1. 1Playground: enable profit_margin, sales_summary and growth_rate.
  2. 2Ask: “How did AI Copilot revenue grow in the North from Jan to Mar, and what was the Q1 margin?”
  3. 3Watch the trace: how many tool calls? In what order? With which arguments?
  4. 4Code Lab → Exercise 3: implement profit_margin + a second tool of your own.
Open Agent Playground Exercise 3 in Code Lab

Reference solution — labs/ex3_tools_agent.py (verified on agent-framework-core 1.26)

ex3_tools_agent.py
1"""Exercise 3 — Python functions as agent tools (Module 3)."""
2
3import asyncio
4from pathlib import Path
5from typing import Annotated
6
7import pandas as pd
8from pydantic import Field
9
10from agent_framework import Agent, tool
11from common import make_client
12
13SALES = pd.read_csv(Path(__file__).parent / "data" / "sales.csv")
14
15
16@tool
17def profit_margin(
18 revenue: Annotated[float, Field(description="Total revenue")],
19 cost: Annotated[float, Field(description="Total cost")],
20) -> str:
21 """Calculate profit and profit margin percentage."""
22 profit = revenue - cost
23 margin = (profit / revenue) * 100 if revenue else 0
24 return f"profit={profit:,.0f}, margin={margin:.1f}%"
25
26
27@tool
28def sales_summary(
29 region: Annotated[str | None, Field(description="North or South; omit for all")] = None,
30 product: Annotated[str | None, Field(description="Cloud Suite or AI Copilot; omit for all")] = None,
31) -> str:
32 """Return monthly revenue, cost and units from the company sales dataset."""
33 df = SALES
34 if region:
35 df = df[df.region.str.lower() == region.lower()]
36 if product:
37 df = df[df["product"].str.lower() == product.lower()]
38 if df.empty:
39 return "No rows match that filter."
40 return df.groupby("month")[["units", "revenue", "cost"]].sum().to_string()
41
42
43@tool(approval_mode="never_require")
44def growth_rate(
45 start: Annotated[float, Field(description="Starting value")],
46 end: Annotated[float, Field(description="Ending value")],
47) -> str:
48 """Percentage growth between two values."""
49 return f"{((end - start) / start) * 100:.1f}%"
50
51
52async def main() -> None:
53 agent = Agent(
54 client=make_client(),
55 name="FinanceAgent",
56 instructions=(
57 "You are a finance analyst. ALWAYS use tools for numbers — never do mental math. "
58 "Show the figures you used."
59 ),
60 tools=[profit_margin, sales_summary, growth_rate],
61 )
62
63 question = "How did AI Copilot revenue grow in the North from Jan to Mar, and what was the Q1 margin?"
64 response = await agent.run(question)
65 print(response.text)
66
67 # Peek at what happened under the hood: function calls & results are messages too
68 for message in response.messages:
69 for content in message.contents:
70 if content.type == "function_call":
71 print(f" -> call {content.name}({content.arguments})")
72 elif content.type == "function_result":
73 print(f" <- result {content.result}")
74
75
76if __name__ == "__main__":
77 asyncio.run(main())

Check your understanding

0/3

Q1.Who actually executes a tool function?

Q2.Where does the tool's description shown to the model come from?

Q3.A tool receives an invalid discount of 90%. Best practice?

M2 · First AgentM4 · Memory