Real Studios

LLM Function Calling: How It Works and When to Use It

Watercolor title card for function calling

LLM function calling lets a language model ask your application to run a function, instead of only writing text. The model does not run anything itself. It returns a structured request with a function name and arguments, your code executes it, and the result goes back to the model to produce the final answer. This guide covers the flow step by step, worked examples, the difference from tool use, JSON mode and structured outputs, and the checks a production system needs.

TL;DR

  • Function calling is a loop: you describe functions, the model proposes a call as JSON, your application runs it, and the model uses the result to reply.
  • Function calling and tool use describe the same pattern. Providers use different names and slightly different message formats.
  • JSON mode guarantees valid JSON only. Structured outputs, or function calling with strict mode, enforce a schema on supported models.
  • Treat every proposed call as untrusted input: validate arguments, check authorisation and keep credentials away from the model.
  • Start with one or two low-risk functions, then widen the scope once logging and permissions are in place.

Table of Contents

What LLM function calling is

A language model on its own can only generate text from its training data and the prompt. Function calling extends that. OpenAI's developer documentation describes it as a way for models to interface with external systems and access data outside their training data, using function tools defined by a JSON schema.

The key point is who does what. Kiran Prakash, writing on martinfowler.com, explains that the model does not execute the call. It creates a data structure that describes the call and hands it to a separate program. That program runs the function and processes the result.

This split is what makes the pattern useful in business systems. The model handles language: understanding a request, choosing the right function and extracting parameters from messy wording. Your code handles everything that must be deterministic: database queries, payments, bookings, emails.

How the function calling loop works

The sequence is the same across the major providers. Google's Gemini API documentation and OpenAI's guide both follow it. In plain terms:

  1. Define the functions. Each one has a unique name, a clear description and a JSON schema for its parameters. Hugging Face's documentation lists exactly these three elements for every tool.
  2. Send the prompt with the definitions. The model sees the user's message and the list of available functions.
  3. The model decides. If a function is needed, it returns a structured call: the function name and the arguments. If not, it answers in text.
  4. Your application executes the function. This happens in your own runtime, with your own permissions.
  5. Return the result. You send the output back to the model.
  6. The model writes the final response, using the real data.

The Hugging Face agents course frames the same cycle as Think, Act and Observe. The model works out which action is needed, formats the action with the right parameters and stops generating, then receives the observed result.

A minimal example

Suppose a customer writes: "Where is order 48213?" You define one function:

{
  "name": "get_order_status",
  "description": "Look up the delivery status of an order by its ID.",
  "parameters": {
    "type": "object",
    "properties": {
      "order_id": { "type": "string" }
    },
    "required": ["order_id"]
  }
}

The model does not answer from memory. It returns a call to get_order_status with order_id set to 48213. Your code queries the order system and sends back the status. The model then writes a reply in natural language: for example, that the parcel is with the courier and due tomorrow.

Notice that the model never touched your database. It produced a request, and your code decided whether to honour it.

Why the description matters

The model chooses functions by reading their names and descriptions. Vague descriptions cause wrong choices. Write each description as you would brief a new colleague: what the function does, when to use it and when not to. Keep parameter names literal (order_id, not id1) and mark truly required fields as required.

Function calling vs tool use

They are the same idea under two labels. OpenAI's documentation uses the term tool calling alongside function calling. Anthropic's documentation calls it tool use and describes it as a contract between the application and the model: the application specifies which operations are available and the shape of their inputs and outputs, and the model decides when and how to call them.

The practical differences are in the message format. Anthropic's loop is keyed on a stop reason. The model responds with a tool_use stop reason and tool blocks, the application runs each tool and returns tool_result blocks, and the loop repeats while the stop reason is tool_use. It ends on any other stop reason, such as end_turn or max_tokens.

LLM tool-use loop from call to result

Other providers name the fields differently, but the logic is identical: propose, execute, return, repeat. If you design your own function layer cleanly, switching model providers becomes a matter of adapting the message format, not rewriting your business logic.

Practical examples of function calling

The provider documentation groups use cases into two broad kinds. Google Cloud's Vertex AI documentation names them fetching data and taking action.

Fetching data

  • Current weather for a location.
  • Account details for a user ID.
  • Currency conversion or a lookup in a knowledge base.

Taking action

  • Issuing a refund for a lost order.
  • Submitting a form or updating application state.
  • Scheduling an appointment, creating an invoice or sending an email, all listed in the Gemini API guide.

The Gemini guide adds a third group: extending capabilities, such as handing arithmetic to a calculator or creating a chart.

Business workflows that suit it

The pattern fits any process where a person's request must become a precise system action:

  • Customer service agents that check order status, update a delivery address or raise a ticket.
  • Internal assistants that query a CRM, pull a report or draft and send a follow-up.
  • Operations flows that read an inbox, classify each message and create a record in the right system.
  • Hiring and HR processes, where a request such as moving a candidate to the next stage becomes a status update. Teams planning this kind of recruitment workflow automation usually map the manual steps first, then decide which ones become functions.

Start with read-only functions. They are easy to test and carry little risk. Add write actions once you trust the argument extraction and have confirmation steps in place.

JSON mode, structured outputs and function calling

These three are often confused because all of them involve JSON. They solve different problems.

ApproachWhat it guaranteesBest for
JSON modeOutput is valid JSON, but not that it matches any particular schemaMachine-readable replies where the format can vary
Structured outputsOutput follows a supplied JSON schema on supported modelsFinal responses and pipelines that need consistent fields
Function callingThe model proposes a call, with arguments shaped by your schemaTriggering actions and fetching data from external systems
Function calling with strict modeArguments adhere to a supported schemaProduction tool calls where bad arguments cost money

The OpenAI Help Center states that JSON mode ensures valid JSON but not schema adherence. On supported models, Structured Outputs ensure function-call arguments adhere to the schema when strict: true is set. Where you cannot use strict mode, the same page advises validating with a library and retrying.

Maria Mouschoutzi, in Towards Data Science, describes function calling as designed for cases where the model must trigger an action or pass arguments to a tool. Structured outputs, in her framing, are function calling with a reliability guarantee, which suits production pipelines where consistency matters. JSON mode suits cases where you can live with a variable format.

Which one should you use?

A simple rule works in most projects:

  • The model must call an external system, or choose between several functions: use function calling.
  • The model's reply is the last step and feeds another program: use structured outputs.
  • You only need parseable text and the shape can vary: JSON mode is enough, though a schema is usually the safer choice.

If the model needs a back-and-forth with the user to collect missing parameters, function calling is the natural fit, because the model can ask for the missing field and then make the call.

Validating and securing function calls

A proposed call is a suggestion from a probabilistic system. Your application must treat it the way it treats input from an anonymous web form.

NVIDIA's NeMo Guardrails security guidelines set out the core rules:

  • Parameterise requests to external services and apply strict validation.
  • Give the model no access to authentication information for external resources.
  • Examine outputs for private information before they return to the dispatch layer.

Hugging Face's guide adds that developers should always implement validation and authorisation checks. In practice, that translates into a checklist.

A practical checklist

  1. Validate arguments against the schema on your server, even when strict mode is on. Check ranges, formats and that referenced records exist.
  2. Authorise on behalf of the real user. The function should run with that user's permissions, never with a broad service account the model can steer.
  3. Use an allow-list. Only functions you have registered can be called. Unknown names are rejected.
  4. Keep secrets out of the prompt. API keys and tokens live in your server, not in anything the model sees.
  5. Confirm sensitive actions. Refunds, deletions and outgoing messages should need an explicit confirmation from a person or a rule-based check, not text the model writes about itself.
  6. Log every call, with the arguments, the result and the user, so you can audit behaviour and debug failures.
  7. Cap the loop. Set a maximum number of tool rounds so a confused model cannot loop indefinitely.

For UK businesses handling personal data, build data protection into the function layer too. Decide which fields a function may return, so the model only ever sees what it needs to answer the question.

Common mistakes in production

Most failures we see described in this area come from design choices rather than from the model itself.

  • Too many functions. A long list of overlapping tools makes selection harder. Group related operations and keep each function's purpose distinct.
  • Free-text parameters where an enum would do. If a field has five valid values, list them in the schema.
  • No error path. When a function fails, return a clear error message to the model so it can explain the problem or retry, instead of inventing an answer.
  • Returning huge payloads. Send back only the fields needed. Smaller results are cheaper, faster and safer.
  • Skipping evaluation. Build a set of realistic requests, including ambiguous and hostile ones, and check which function and arguments the model picks each time you change a prompt or model.

Our perspective

Function calling is the point where an AI project stops being a demo and becomes part of how a business runs. A chatbot that only talks is limited. An agent that can check an order, update a record or book a slot saves real time.

In our work on AI agents, automations and integrations for UK businesses, the model is rarely the hard part. The value sits in the integration layer: well-described functions, clean permissions, sensible confirmations and logging. That is where we put our effort.

We favour a short path to something working. A small set of functions around one real workflow, shown as a working demo in days, tells you more than months of planning. From there the scope grows with evidence.

We also believe you should own what is built. Your functions, your schemas and your integration code belong to your business, and they should keep working as models and providers change.

Oded

Build function calling into your business

If you want agents that act on your systems, not just answer questions, our team designs and builds them for UK businesses. We cover AI agents (RAG, voice, chat and email), automations and workflow design, and integrations that connect models to your existing tools. See our AI agent, automation and integration services, or start with a Rapid MVP to get a working version of one workflow in front of your team. For connecting models to the systems you already run, look at our AI integrations and enablement work.

FAQ

Does the LLM actually run the function?

No. The model returns a structured request naming the function and its arguments. Your application runs the function and sends the result back, and the model then writes the final reply. This is why validation and permissions sit in your code.

Is function calling the same as tool use?

In practice, yes. Some providers say function calling and others say tool use or tool calling, and the message formats differ slightly. The underlying loop of propose, execute, return and repeat is the same.

Should I use JSON mode or function calling?

Use function calling when the model must trigger an action or fetch data from an external system. JSON mode only guarantees valid JSON, not a specific schema, so for reliable fields choose structured outputs or strict function calling on supported models.

How do I stop the model calling something it should not?

Register only the functions you want available and reject any other name. Validate arguments on your server, check the user's authorisation before running anything, and require confirmation for sensitive actions. Keep credentials out of the model's reach entirely.

What is a good first function to build?

Pick a read-only lookup tied to a frequent customer or staff question, such as order status or account details. It is easy to test and low risk, and it proves the whole loop before you add actions that change data.

Sources

All guides