New cohort: Agentic AI & LLM Engineering remote internship. Limited seats.Apply now
Lesson 11 of 21 24 minFree

Integrating with Function Calling

Give an LLM tools: describe your functions with JSON Schema, let the model pick one and its arguments, run it safely in code, and answer with real data.

By the end of this lesson you will be able to:

  • Explain what function calling (tool use) is and which problems it solves.
  • Describe a function to a model with a name, a description and a JSON Schema.
  • Run the full loop: model picks a tool → your code runs it → model answers.
  • Make tools safe with validation, least privilege and confirmation.

The problem: models can't look things up or take action

A student asks our study buddy: "When is my next Physics class?". The model has no idea, because timetables live in the school's database, not in its training data. If you just ask, it may even invent an answer. And when you ask for JSON, it sometimes returns slightly different shapes each time.

Function calling (also called tool use) fixes both problems. You tell the model which functions your app has. When a question needs one, the model replies with which function to call and with what arguments, in clean, structured JSON. Your code runs the function and gives the result back, and the model writes the final answer using real data.

See it happen

The model sits at the centre, surrounded by four tools your app provides. Ask a question and follow the request out to the right tool and back again.

The key insight: the model never runs anything itself. It only asks for a function call. Your code decides whether to run it, runs it, and controls exactly what data goes back. That's what makes tools safe enough for real apps.

Step 1: describe your functions

Each tool has a name, a clear description (the model reads it to decide when to use the tool!) and its parameters as JSON Schema:

tools = [{
    "type": "function",
    "function": {
        "name": "get_timetable",
        "description": "Get the next class for a student and subject. Use for any question about class times or rooms.",
        "parameters": {
            "type": "object",
            "properties": {
                "student_id": {"type": "string", "description": "School ID like S1042"},
                "subject": {"type": "string", "enum": ["Maths", "Physics", "Chemistry", "Biology", "English"]}
            },
            "required": ["student_id", "subject"]
        }
    }
}]

Step 2: the loop

With the OpenAI Python library (run on your own machine with a key, as in Lesson 6):

import json

messages = [{"role": "user", "content": "When is my next Physics class? My ID is S1042."}]
first = client.chat.completions.create(model="gpt-4o-mini", messages=messages, tools=tools)
msg = first.choices[0].message

if msg.tool_calls:
    messages.append(msg)                                   # keep the model's tool request
    for call in msg.tool_calls:
        args = json.loads(call.function.arguments)        # e.g. {"student_id": "S1042", "subject": "Physics"}
        result = get_timetable(**args)                     # YOUR function, YOUR database
        messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})
    final = client.chat.completions.create(model="gpt-4o-mini", messages=messages, tools=tools)
    print(final.choices[0].message.content)
else:
    print(msg.content)                                     # no tool needed

Other providers (Anthropic, Google, Azure OpenAI) use the same idea with slightly different field names.

What function calling is great for

  • Live data: weather, timetables, marks, stock levels, order status.
  • Actions: book a slot, create a ticket, send a reminder (with care, see below).
  • Exact work: maths, unit conversion and date calculations, done by real code instead of the model guessing.
  • Reliable structured output: even when nothing is "called", forcing the model to fill a function's schema gives you consistent JSON every time.
  • Agents: chaining several tool calls to finish a bigger task. This is the foundation of Lesson 17.

Making tools safe

  • Validate every argument before running anything: types, allowed values, lengths. The model can make mistakes, and attackers can try to trick it (Lesson 13).
  • Least privilege: the timetable tool should only read this student's timetable, using the logged-in student's ID from your session, not an ID the model typed.
  • Confirm risky actions: anything that sends, pays, deletes or changes data needs a human "Yes, do it".
  • Keep tools few and well described: a handful of clear tools works better than dozens of vague ones.

Hands-on

Your task: the model returned the tool_call below. Parse its JSON arguments, look up the function by name in TOOLS, call it with the arguments, and store the result in result. Expected last line: Answer data: {'day': 'Tuesday', 'time': '10:30', 'room': 'Lab 2'}.

import json

def get_timetable(student_id, subject):
    table = {("S1042", "Physics"): {"day": "Tuesday", "time": "10:30", "room": "Lab 2"}}
    return table.get((student_id, subject), {"error": "not found"})

def calculate(expression):
    return {"error": "not used in this exercise"}

TOOLS = {"get_timetable": get_timetable, "calculate": calculate}

# What the model sent back (arguments arrive as a JSON *string*):
tool_call = {"name": "get_timetable", "arguments": '{"student_id": "S1042", "subject": "Physics"}'}

# TODO: args = parse tool_call["arguments"] with json.loads
# TODO: fn = TOOLS[...]; result = fn(**args)
result = None

print("Tool:", tool_call["name"])
print("Answer data:", result)
Show solution
args = json.loads(tool_call["arguments"])
fn = TOOLS[tool_call["name"]]
result = fn(**args)

Your task: complete validate() using the schema: every required field must be present, subject must be one of the allowed values, and no unknown fields are allowed. It returns a list of problems (empty = safe to run). Expected last line: Rejected 3 unsafe calls.

schema = {
    "required": ["student_id", "subject"],
    "allowed": {"student_id", "subject"},
    "subject_values": {"Maths", "Physics", "Chemistry", "Biology", "English"},
}

calls = [
    {"student_id": "S1042", "subject": "Physics"},                     # fine
    {"student_id": "S1042"},                                            # missing subject
    {"student_id": "S1042", "subject": "Hacking"},                     # not allowed
    {"student_id": "S1042", "subject": "Maths", "admin": True},        # unknown field
]

def validate(args):
    problems = []
    # TODO 1: for each required field missing from args, add "missing <field>"
    # TODO 2: if "subject" in args and it is not in schema["subject_values"], add "bad subject"
    # TODO 3: for each key in args not in schema["allowed"], add "unknown field <key>"
    return problems

rejected = 0
for args in calls:
    problems = validate(args)
    print("RUN " if not problems else "STOP", args, problems)
    rejected += bool(problems)
print(f"Rejected {rejected} unsafe calls")
Show solution
    for field in schema["required"]:
        if field not in args:
            problems.append(f"missing {field}")
    if "subject" in args and args["subject"] not in schema["subject_values"]:
        problems.append("bad subject")
    for key in args:
        if key not in schema["allowed"]:
            problems.append(f"unknown field {key}")

Check your understanding

When the model "calls a function", what actually happens?

  1. The model runs the Python function on its servers
  2. The model returns the function name and JSON arguments, and your code runs it
  3. The function is added to the model's training data
  4. The API calls your database directly

The model only requests a call. Your app validates and executes it, then sends the result back.

How does the model decide which tool to use?

  1. Randomly
  2. Alphabetically
  3. Always the first tool in the list
  4. From each tool's name, description and parameters

Clear names and descriptions are part of prompt engineering for tools.

A send_fee_reminder tool emails parents. What's the safest design?

  1. Let the model send emails whenever it wants
  2. Give it access to all school email accounts
  3. Validate arguments and require a staff member to confirm before sending
  4. Hide the tool description so it's used less

Actions with real-world effects need validation and human confirmation.

Key takeaways

  • Function calling lets models request tools for live data, actions and exact work.
  • Describe each tool with a clear name, description and JSON Schema.
  • The loop: model returns tool_call → your code validates and runs it → result goes back → final answer.
  • Validate arguments, use least privilege, and confirm risky actions.

Next: designing a user experience people trust and enjoy.

Your progress is saved in this browser.

Adapted from Lesson 11 of Microsoft's "Generative AI for Beginners" (MIT License), rewritten and extended by Aiprojects4U. View source