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.
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 FunctionTooldef 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 description1from typing import Annotated2from pydantic import Field3from agent_framework import Agent, tool45@tool6def 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 - cost12 return f"profit={profit:,.0f}, margin={profit / revenue * 100:.1f}%"1314agent = Agent(client=client, instructions="ALWAYS use tools for numbers.",15 tools=[profit_margin, sales_summary, growth_rate])
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.
1SALES = pd.read_csv("data/sales.csv")23@tool4def 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 = SALES10 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()
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.
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
The model requests calls; MAF executes them and loops until a text answer.
Type hints + Field descriptions + docstrings become the tool schema — write them well.
Return readable errors so the model can self-correct.
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
- 1Playground: enable profit_margin, sales_summary and growth_rate.
- 2Ask: “How did AI Copilot revenue grow in the North from Jan to Mar, and what was the Q1 margin?”
- 3Watch the trace: how many tool calls? In what order? With which arguments?
- 4Code Lab → Exercise 3: implement profit_margin + a second tool of your own.
Reference solution — labs/ex3_tools_agent.py (verified on agent-framework-core 1.26)
1"""Exercise 3 — Python functions as agent tools (Module 3)."""23import asyncio4from pathlib import Path5from typing import Annotated67import pandas as pd8from pydantic import Field910from agent_framework import Agent, tool11from common import make_client1213SALES = pd.read_csv(Path(__file__).parent / "data" / "sales.csv")141516@tool17def 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 - cost23 margin = (profit / revenue) * 100 if revenue else 024 return f"profit={profit:,.0f}, margin={margin:.1f}%"252627@tool28def 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 = SALES34 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()414243@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}%"505152async 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 )6263 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)6667 # Peek at what happened under the hood: function calls & results are messages too68 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}")747576if __name__ == "__main__":77 asyncio.run(main())
Check your understanding
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?