Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 41/ 160
03. AI Agents

Tool Calling

Function/tool schemas that let models invoke APIs, search, and code execution safely.

BeginnerFunctions · Schema · Results3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

The model says "please run this function with these inputs", your program runs it, and tells the model what happened.

Think of it like…

A manager who can't touch the warehouse but can fill in request forms: the form (schema) says exactly what fields are needed, staff (your code) check and carry out the request, and the result comes back on paper for the manager to act on.

Where you’ve seen it

A support assistant has three tools: get_order(order_id), refund_order(order_id, amount, reason) and search_help_articles(query). For "Where's order 8841?" the model returns get_order({"order_id": "8841"}); the app calls the order API and returns the JSON; the model replies with the delivery date. The refund tool checks server-side that the amount is at most the order total and that the caller owns the order, and requires approval above ₹5,000, whatever the model asks for.

Words you’ll hear

Tool schema
Name, description and JSON Schema of parameters that tell the model how to call a function.
Tool call
The model's structured request to run a tool with specific arguments.
Tool result
The output your code sends back for the model to read.
tool_choice
API setting forcing, allowing or forbidding tool use (auto, required, a named tool, none).

Visual diagram

Loading interactive diagram

Theory & deep dive

Designing tools the model can use

The description is the model's only guide: say what the tool does, when to use it and when not to, with parameter descriptions, formats and examples ("order_id: the 4–10 digit number from the confirmation email"). Use narrow, typed parameters with enums and required fields ("status": {"enum": ["open", "closed"]}), name tools by action (get_order, not orders), and prefer a few well-scoped tools over dozens of overlapping ones. Strict or structured modes guarantee arguments match the schema, but you still validate meaning (does this order belong to this user?).

Return compact, informative results: trim large payloads, include identifiers the model may need next, and put errors in the result in plain language ("error": "Order not found. Check the number or ask the customer to confirm it.") rather than crashing the loop. Models may call several independent tools in parallel in one turn; execute them concurrently and return all results.

A tool definition

{"name": "get_order", "description": "Look up one order by its 4-10 digit order number. Use when the customer asks about delivery or status. Do not use for refunds.", "parameters": {"type": "object", "properties": {"order_id": {"type": "string", "pattern": "^[0-9]{4,10}$"}}, "required": ["order_id"], "additionalProperties": false}}

Key takeaway: Clear descriptions, tight schemas, compact results and helpful errors.

Safety, permissions and testing

Treat model output as untrusted input. Check arguments against the schema and business rules, authorise with the end user's identity (not a powerful service account the model can steer), apply rate limits and per-tool permissions, and classify tools by risk: read-only tools can run freely; writes need validation and logging; irreversible or financial actions need human approval. Make mutating tools idempotent (accept an idempotency key) so retries don't double-charge. Tool results can contain injected instructions (a web page saying "ignore previous instructions"), so never let results change permissions.

Test tool use with evaluations: for a set of realistic requests, check that the right tool is chosen, arguments are correct, no tool is called when none is needed, and failures are handled. Log every call and result for audit and debugging, and monitor tool error rates. Use tool_choice to force a specific tool when your workflow demands it, and limit the toolset per request so the model sees only the relevant tools.

Server-side guard for a risky tool

def refund_order(order_id, amount, reason, user): order = db.get(order_id); assert order.user_id == user.id; assert 0 < amount <= order.total; if amount > 5000: return {"status": "pending_approval"}; return payments.refund(order_id, amount, idempotency_key=f"{order_id}-{reason_hash}")

Key takeaway: Authorise as the user, validate, classify risk, make writes idempotent, and evaluate tool use.

How it works, step by step

Step 1 of 4
Developer

1. Define tools and schemas

Write names, descriptions with when-to-use guidance, and JSON Schemas with types, enums and required fields.

get_order(order_id: string)
Key numbers at this step
Few
focused tools

When to use it & trade-offs

What it is

Tool calling (function calling) lets a model request actions in your software. You describe each tool with a name, a description and a JSON Schema for its arguments. When the model decides a tool is needed, it doesn't run anything: it returns a tool call (name plus arguments). Your application validates the arguments, executes the function, and sends the tool result back, and the model uses it to continue or answer. Tools are how models reach live data, databases, APIs and code execution.

Why it matters: A language model alone can't check an order status, query a database or send an email, and its knowledge is frozen. Tool calling turns it into a controller of real systems, which is also where the risk is: the model chooses the arguments, so every tool is an attack and error surface. Reliable agents depend on well-designed schemas, argument validation, permissions and error handling.

When to reach for it

  • Looking up live data and records
  • Triggering actions with approval for risky ones
  • Running calculations or code in a sandbox

When to avoid or be careful

  • Powerful credentials shared across users
  • Dozens of overlapping tools with vague descriptions
  • Executing model-supplied arguments without validation

Ways to get structured actions from a model

Native tool calling
Best for: Most agents and assistants

Strengths: Reliable structured calls; parallel calls; provider support.

Watch out: Provider-specific details; schema limits.

Prompted JSON in text
Best for: Models without tool support

Strengths: Works anywhere.

Watch out: Fragile parsing; more retries.

Code execution as a tool
Best for: Data analysis, calculations, flexible logic

Strengths: Very general.

Watch out: Needs a sandbox; larger risk surface.

Interview signals & numbers to know

When this topic comes up

  • “How do you let the LLM call our API safely?”
  • “The model calls the wrong tool”
  • “What's the difference between function calling and structured output?”
  • tool_choice and parallel tool calls
  • Idempotent tools

Benchmarks & rules of thumb

~10–20 -
tools before selection accuracy often degrades
₹5,000 -
approval threshold in the refund example
1 per risk -
tier: read, write, irreversible

Common mistakes & follow-ups

Common interview mistakes

  • Running the model's amount argument straight into a payments API.
  • Using one admin API key for every user's tool calls.
  • Returning a 50,000-token API response as the tool result, flooding the context.

Likely interviewer follow-ups

  • How would you design the tools for a customer-support agent?
  • How do you stop a model from misusing a refund tool?
  • What do you return to the model when a tool fails?
Interview tip: Say "the model proposes, my code validates and executes". That one sentence frames tool calling as a trust boundary, which is what interviewers probe.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Tool Calling with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
MRR and nDCG
Next topic
The Agent Loop