LLM function calling: how tool use works, with code you can run

LLM function calling: how tool use works, with code you can run

LLM function calling (also called tool use) lets a language model ask your code to run a function: the model returns the function name and JSON arguments, your application executes it and sends the result back. This guide covers schemas, the request loop, parallel calls, errors and security, with Python you can run against Claude or OpenAI.

In shortTL;DR
  • The model never runs anything. It returns a structured call; your code decides whether to execute it and returns the result in the next request.
  • Tool descriptions matter more than anything else: Anthropic recommends at least 3 to 4 sentences per tool, covering what it does, when to use it and what it returns.
  • Turn on strict schemas (strict: true) so arguments always match your JSON Schema, and still check permissions and business rules in code.
  • Return all results from one turn in a single message, report failures as errors the model can read, and cap the number of loop iterations.
  • Treat every tool result as untrusted input and every write action as something the model can be tricked into calling.

What is LLM function calling?

LLM function calling is a feature of model APIs that lets the model request a call to a function you have described, instead of only writing text. You send the model a list of functions with a name, a description and a JSON Schema for the arguments. When the model decides one of them would help, it replies with a structured call such as get_order_status({"order_id": "8812"}). Your code runs the function and sends the result back, and the model uses it to answer.

The key point that trips up newcomers: the model does not execute anything. Anthropic's tool use overview describes it as Claude returning "a structured call that your application runs." The model is choosing and filling in a form. Your application stays in control of what actually happens, which is also why the security of a tool-using system lives in your code, not in the prompt.

The vocabulary varies by vendor:

TermWho uses it
Function callingOpenAI, Google Gemini
Tool useAnthropic
Tool callingMany open-source models and frameworks

All three mean the same thing. Function calling is what turns a chatbot into an agent: the ability to look up live data, query a database, create a ticket or edit a file. Our explainer on what AI agents are covers the bigger picture.

How does the function calling loop work?

Function calling is a loop of at least two API requests: one where the model asks for a call, and one where you hand back the result. An agent repeats that loop until the model answers without asking for another tool.

  1. Send the request with tools. Include the user's message and a tools list with each function's name, description and parameter schema.
  2. Read the response. If the model wants a tool, the response says so: Claude sets stop_reason to tool_use and includes tool_use blocks; OpenAI's Responses API returns function_call items.
  3. Validate and execute. Parse the arguments, check that this user is allowed to do this, and run your function.
  4. Send the result back. Append the model's turn to the history, then add the result linked by its ID (tool_use_id for Claude, call_id for OpenAI).
  5. Repeat until done. Call the model again with the full history. It either requests more tools or writes the final answer.

Each tool also costs tokens. Tool names, descriptions and schemas count as input tokens on every request, and Claude adds a tool use system prompt on top. Anthropic's pricing table on the overview page lists 286 extra tokens for Claude Opus 5.5 when tools are present, before your own definitions.

286extra system prompt tokens when tools are present (Claude Opus 5.5)
3 to 4sentences per tool description, Anthropic's minimum advice
< 20functions at the start of a turn, OpenAI's soft suggestion
10 to 20active tools, the maximum Gemini's docs recommend
Sources: Claude tool use docs, OpenAI function calling guide, Gemini function calling docs (November 2026)

How do you write a function schema the model uses correctly?

A function definition has three parts: a name, a description and a JSON Schema for the arguments. The description does most of the work. Anthropic's define tools guide calls detailed descriptions "by far the most important factor in tool performance" and asks for at least 3 to 4 sentences per tool.

Here is a weak definition and a strong one for the same function:

weak
{  "name": "get_order",  "description": "Gets an order.",  "input_schema": {    "type": "object",    "properties": { "id": { "type": "string" } }  }}
strong
{  "name": "orders_get_status",  "description": "Look up the shipping status of one customer order by its order number. Use this when the user asks where an order is, when it will arrive, or whether it shipped. Returns status, carrier, tracking number and estimated delivery date. Does not return prices or payment details; it cannot change or cancel an order.",  "strict": true,  "input_schema": {    "type": "object",    "properties": {      "order_id": {        "type": "string",        "description": "The order number as shown on the receipt, digits only, for example 8812."      }    },    "required": ["order_id"],    "additionalProperties": false  }}

The rules that make the difference, drawn from the Anthropic, OpenAI and Gemini guides:

  • Say when to use it and when not to. Overlapping tools are the main cause of wrong picks.
  • Use enums for fixed values. "enum": ["celsius", "fahrenheit"] beats a free string the model can misspell.
  • Namespace names when you have several services. github_list_prs and slack_send_message are unambiguous; list and send are not.
  • Consolidate. Anthropic suggests one tool with an action parameter over separate create_pr, review_pr and merge_pr tools.
  • Don't ask the model for what you already know. OpenAI's guide makes this point: if your code knows the user ID, inject it yourself instead of making it a parameter.
  • Return only what the model needs. Short results with stable IDs keep the context small and the next step clear.

Turn on strict mode for every custom tool. With strict: true, Claude constrains generation so tool inputs match your schema: per the strict tool use docs, passengers comes back as 2, never "two". OpenAI's strict mode needs additionalProperties: false on every object and every property listed in required, with optional fields expressed as nullable. The same schema rules are covered in depth in our guide to LLM structured output.

How does function calling differ between Claude, OpenAI and Gemini?

The three major APIs follow the same loop but use different field names and controls. If you switch providers, these are the parts you rewrite.

Claude (Messages API)OpenAI (Responses API)Gemini
Schema fieldinput_schemaparametersparameters
Model asks withtool_use block, stop_reason: "tool_use"function_call item with call_idfunction call with call_id
You reply withtool_result block in a user messagefunction_call_output itemfunction result step
Force a calltool_choice: any or tool (not on every model)tool_choice: required or a named functiontool_choice: any
One call per turndisable_parallel_tool_use: true inside tool_choiceparallel_tool_calls: falseSee the Gemini docs
Schema guaranteestrict: truestrict: truevalidated mode

Two gotchas worth knowing as of November 2026:

  • Forced tool use is not available on every Claude model. The define tools page says Claude Opus 5.5, Sonnet 5.5 and Fable 5.1 return a 400 error for tool_choice of any or tool. Use auto with strict tools, or structured outputs if you only need a JSON result.
  • OpenAI returns arguments as a string. You must json.loads() them, and the OpenAI guide notes that reasoning items returned alongside tool calls must be passed back in the next request.

Python example: a complete function calling loop with Claude

The loop below handles any number of tools, parallel calls and errors, and stops after a fixed number of turns. It uses the official anthropic SDK; install it with pip install anthropic and set ANTHROPIC_API_KEY.

agent_loop.py
import jsonimport anthropicclient = anthropic.Anthropic()MODEL = "claude-sonnet-5-5"def orders_get_status(order_id: str) -> dict:    # Replace with a real lookup. Check that the signed-in user owns this order here.    return {"order_id": order_id, "status": "shipped", "carrier": "UPS", "eta": "2026-11-04"}HANDLERS = {"orders_get_status": orders_get_status}TOOLS = [{    "name": "orders_get_status",    "description": (        "Look up the shipping status of one customer order by its order number. "        "Use this when the user asks where an order is or when it will arrive. "        "Returns status, carrier and estimated delivery date. "        "It cannot change, refund or cancel an order."    ),    "strict": True,    "input_schema": {        "type": "object",        "properties": {"order_id": {"type": "string", "description": "Order number, digits only."}},        "required": ["order_id"],        "additionalProperties": False,    },}]def run_tool(block) -> dict:    try:        output = HANDLERS[block.name](**block.input)        return {"type": "tool_result", "tool_use_id": block.id, "content": json.dumps(output)}    except Exception as exc:  # report the failure to the model instead of crashing        return {            "type": "tool_result",            "tool_use_id": block.id,            "content": f"{type(exc).__name__}: {exc}",            "is_error": True,        }def ask(question: str, max_turns: int = 8) -> str:    messages = [{"role": "user", "content": question}]    for _ in range(max_turns):        response = client.messages.create(            model=MODEL, max_tokens=2048, tools=TOOLS, messages=messages        )        if response.stop_reason != "tool_use":            return "".join(b.text for b in response.content if b.type == "text")        messages.append({"role": "assistant", "content": response.content})        results = [run_tool(b) for b in response.content if b.type == "tool_use"]        messages.append({"role": "user", "content": results})  # all results in one message    raise RuntimeError("Stopped after too many tool turns")print(ask("Where is my order 8812?"))

Three details in that code come straight from the handle tool calls docs: the assistant turn is appended unchanged, the tool_result blocks come first in the next user message, and failures go back with is_error: true so Claude can retry or explain. If you would rather not write the loop, the Anthropic SDKs include a tool runner that executes your tools and sends results back for you.

The same round trip with OpenAI's Responses API looks like this. Note the string arguments and the call_id:

openai_loop.py
import jsonfrom openai import OpenAIclient = OpenAI()tools = [{    "type": "function",    "name": "orders_get_status",    "description": "Look up the shipping status of one order by its order number.",    "strict": True,    "parameters": {        "type": "object",        "properties": {"order_id": {"type": "string"}},        "required": ["order_id"],        "additionalProperties": False,    },}]items = [{"role": "user", "content": "Where is my order 8812?"}]response = client.responses.create(model="gpt-5.4", tools=tools, input=items)items += response.output  # keep reasoning items and calls in the historyfor item in response.output:    if item.type == "function_call":        args = json.loads(item.arguments)        result = orders_get_status(**args)  # same handler as above        items.append({"type": "function_call_output", "call_id": item.call_id, "output": json.dumps(result)})final = client.responses.create(model="gpt-5.4", tools=tools, input=items)print(final.output_text)
Developer working at a laptop in front of two monitors full of code
The model proposes the call; your code decides whether it runs.

How do parallel function calls work?

Parallel function calling means the model asks for several calls in one response, for example the weather in three cities or a customer record plus their last five orders. All three major APIs support it, and it is on by default for Claude.

How you execute the batch is up to you. Anthropic's parallel tool use page says the API does not prescribe an order: run independent, read-only calls concurrently with asyncio.gather or Promise.all, and run calls with side effects or ordering needs one after another.

The mistake that quietly breaks parallelism is the reply format. Send all results in a single user message, each matched by ID. Anthropic notes that sending a separate user message per result "teaches" Claude to stop making parallel calls. If calls in one batch depend on each other and you run them sequentially, stop at the first failure and return is_error: true for the calls you skipped.

To turn parallelism off, set disable_parallel_tool_use: true inside Claude's tool_choice object (it is not a top-level parameter), or parallel_tool_calls: false with OpenAI.

How should you handle errors in function calling?

Report every failure back to the model as a tool result instead of throwing, and write the error so the model knows what to do next. A model that sees "Rate limit exceeded. Retry after 60 seconds." can adapt; a model that sees "failed" guesses.

FailureWhat to do
Your function throws (network, 500, timeout)Return the message with is_error: true
Arguments are wrong or missingUse strict mode; otherwise return an error naming the missing field. Claude retries 2 to 3 times before apologizing, per the docs
Unknown tool nameReturn an error listing valid tools; strict mode prevents this on Claude
Response cut off mid-call (stop_reason: max_tokens)Retry the request with a higher max_tokens
Model loops on the same callCap iterations, as max_turns does above, and log the trace
Permission deniedReturn a clear refusal; never fall back to a broader credential

Log every call with its arguments, result, latency and token usage. When an agent misbehaves, the trace of tool calls is the first thing you will want. Our guide to LLM observability covers what to record.

How do you keep function calling secure?

Assume the model can be convinced to call any tool you give it with any arguments the schema allows, then design so that this is safe. Prompt injection makes this a practical concern: a web page, email or support ticket that ends up in a tool result can contain instructions aimed at the model.

The OWASP Top 10 for LLM applications calls the resulting risk excessive agency and names three root causes: excessive functionality, excessive permissions and excessive autonomy. Its mitigations translate into concrete rules:

  1. Expose the minimum. Offer orders_get_status, not run_sql. Avoid open-ended tools such as a general shell or URL fetcher unless you sandbox them.
  2. Authorize in code. Check that the signed-in user may read that order or send that email inside the function, every time. The prompt is not an access control.
  3. Use the user's own scope. Call downstream APIs with the end user's credentials or a least-privilege service account, not an admin key.
  4. Confirm high-impact actions. Payments, deletions, outbound messages and anything irreversible should wait for a human click.
  5. Keep untrusted text in tool results. Anthropic's docs advise keeping external content inside tool_result blocks rather than system prompts or user text.
  6. Limit and log. Rate limits, budgets and logs don't prevent misuse, but they cap the damage and show you what happened.
Warning

Never put secrets, API keys or other customers' data in tool descriptions or schemas. They are sent to the model on every request, and Anthropic caches compiled strict schemas separately from your messages.

Coding agents are the extreme case: their tools are a shell and a file editor. Our guide to prompt injection in coding agents covers that threat model, and running agents on an isolated machine, such as an Orkio box, keeps their blast radius away from your laptop.

Function calling vs structured output vs MCP: which do you need?

Use function calling when the model must decide whether and which action to take, structured output when you only need the answer in a fixed JSON shape, and MCP when you want to share tools across many apps and agents.

You want toUse
Pull fields from an invoice into JSONStructured output
Let a support bot look up orders or open ticketsFunction calling
Give Claude Code, Cursor and your own agent the same GitHub toolsAn MCP server
Run code or search the web without hosting itThe provider's hosted tools

These layers stack. An MCP client discovers tools from a server and then passes them to the model through ordinary function calling. If MCP is new to you, start with what MCP is.

Checklist: ship your first function calling feature

  1. Start with one or two read-only tools. Add write actions only after the read path works.
  2. Write 3 to 4 sentence descriptions that say what each tool does, when to use it and what it returns.
  3. Set strict: true and additionalProperties: false, and use enums for fixed values.
  4. Inject user IDs and tenant IDs from your session, never from model arguments.
  5. Authorize inside every handler and require confirmation for irreversible actions.
  6. Return errors as tool results with instructions, and cap the loop at a fixed number of turns.
  7. Send all results from one turn in a single message.
  8. Log every call, then test with 20 to 30 real user requests, including ones that should not trigger a tool.

If you want to go further and build a full agent around this loop, our walkthrough on building an AI agent in Python picks up where this checklist ends.

Frequently asked questions

Is function calling the same as tool calling?

Yes. OpenAI and Google mostly say function calling, Anthropic says tool use, and many open-source projects say tool calling. All three describe the same mechanism: the model emits a structured request to call a named function with JSON arguments, and your application runs it.

Does the LLM execute the function itself?

No, not for functions you define. The model only produces the function name and arguments. Your code runs the function and sends the output back. Some providers also offer hosted tools, such as web search or code execution, which run on the provider's servers instead of yours.

How many functions can I give a model at once?

There is no single hard limit, but accuracy drops as the list grows. OpenAI suggests keeping fewer than 20 functions available at the start of a turn, and Google's Gemini docs say to keep the active set to 10 to 20 tools. For larger catalogs, use tool search or load tools per task.

What is the difference between function calling and MCP?

Function calling is the model capability: the model emits a call and your code handles it. MCP (Model Context Protocol) is a standard way to package tools on a server so any compatible client can discover and call them. An MCP client still uses function calling under the hood to let the model pick a tool.

Can open-source models do function calling?

Many can, but quality varies a lot by model and by the chat template your inference server uses. The Berkeley Function Calling Leaderboard compares models on this skill. Test with your own tools and prompts before you rely on a model in production.

Why does the model call the wrong function or invent arguments?

Usually the descriptions are too short or two tools overlap. Rewrite descriptions to say when each tool should and should not be used, use enums for fixed values, merge overlapping tools, and turn on strict mode. If a required value is missing from the conversation, tell the model in the system prompt to ask the user instead of guessing.

SOURCES

  1. Claude docs: Tool use with Claude
  2. Claude docs: Define tools
  3. Claude docs: Handle tool calls
  4. Claude docs: Parallel tool use
  5. OpenAI API docs: Function calling
  6. Gemini API docs: Function calling
  7. OWASP Top 10 for LLM Applications: LLM06:2025 Excessive Agency
  • #function calling
  • #tool use
  • #llm api
  • #ai agents
Orkio team

The team building Orkio. We write about putting AI to work: coding agents that run overnight, always-on boxes and pull requests ready by morning.

Keep reading

All posts

07:06 · YOU MERGED #128

Go to sleep. Wake up to pull requests.

Start for $19 a month
© 2026 Orkio · Hosted in Europe TürkçeStatus