Foundations to Frontier
Tests
F. NLP and Large Language Models › F11 Agents and Tool Use

Function calling

Function calling lets a language model act. The application describes the available tools as JSON schemas; the model replies with a structured call naming a tool and its arguments. The application runs the call and returns the result, and the model continues. This page covers tool schemas, parsing, validation, error feedback, parallel calls and choosing among many tools. In the exercises you write a tool schema, a robust parser and a dispatcher that returns readable errors. You then simulate 1000 tasks with 200 tools. Offering all 200 tools cost 30000 tokens and picked the right tool 67% of the time, under an assumed accuracy that falls as more tools are offered. Retrieving 10 candidate tools found the right one 87% of the time and chose correctly 82%. Free-form calls were fully correct 77% of the time. Validation with error feedback reached 92% at 1.21 calls per task, and constrained decoding reached 93% at one call. Neither caught well-formed but wrong values.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Giving the model a phone and a directory

A language model on its own can only write text. Function calling gives it a directory of services it may call, such as ‘read a sensor’, ‘search the manual’ or ‘book a slot’, each with a form describing what to fill in. The model fills in a form, the application makes the call and hands back the answer, and the model carries on. The demo shows a catch: the longer the directory, the more often the model picks the wrong entry, and the more of its memory the directory fills.

Agent lab
With 20 tools the model picks the right one about 83% of the time, and the tool descriptions take about 3000 tokens of context. Offer only the tools a task needs, or retrieve them.
Why engineers care

Every agent, from a coding assistant to a robot task planner, is built on function calling: the model decides, the application acts.

📝 Quick check (Level 0)
0/3 answered
  1. 1. In function calling the model outputs…
  2. 2. Who actually runs the tool?
  3. 3. Offering many tools…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Tool definitions: name, description and a JSON schema for the parameters; descriptions matter as much as prompts.
  • The loop: user message → model returns tool call(s) → application validates and executes → result appended as a tool message → model answers or calls again.
  • Parallel calls: several independent calls in one turn save round trips.
  • Forcing: tool_choice can require a call, a specific tool, or none.
  • Structured outputs: constrained decoding against the schema guarantees valid JSON and types (F9-3); validation and error feedback catch the rest.
  • Many tools: accuracy drops and context fills as tool count grows; retrieve relevant tools per request, or group them behind sub-agents.
  • Training: models learn tool use from fine-tuning on call traces (Toolformer, Gorilla, ToolLLM).
  • Security: tool results are untrusted input; never let them grant permissions (F11-6).
📝 Quick check (Level 1)
0/3 answered
  1. 1. A tool result is returned to the model as…
  2. 2. Constrained decoding guarantees…
  3. 3. With hundreds of tools, a good practice is…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Implementing tool use

Exercise 1.

  • Build an OpenAI-style tool schema.
  • Parse a tool call robustly.
  • Dispatch to Python functions, returning readable errors.

Practice.

  • All major APIs support tools: OpenAI tools, Anthropic tool use, Gemini function calling; open models via vLLM or Ollama with tool templates.
  • Write descriptions for the model: when to use the tool, units, examples, what not to do.
  • Validate arguments against the schema before running anything; return errors as tool results so the model can retry.
  • Make tools idempotent and safe by default; require confirmation for irreversible actions.
  • Log every call and result; cap the number of calls per task.
import anthropic, json
client = anthropic.Anthropic()
tools = [{"name": "get_temp", "description": "Read a temperature sensor in degrees C.",
          "input_schema": {"type": "object", "properties": {"sensor": {"type": "string"}}, "required": ["sensor"]}}]
msgs = [{"role": "user", "content": "Is sensor T3 above 80 C?"}]
resp = client.messages.create(model="claude-sonnet-5-5", max_tokens=500, tools=tools, messages=msgs)
for block in resp.content:
    if block.type == "tool_use":
        result = dispatch(registry, block.name, block.input)
🐍 Exercise 1: schema, parser and dispatcher
Write a tool schema builder, a tool-call parser and a dispatcher that returns readable errors.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Tool argument errors should be…
  2. 2. Irreversible actions need…
  3. 3. Good tool descriptions say…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Where calls fail. A call can name the wrong tool, be malformed, miss required fields, have wrong types or invalid enum values, or be well-formed with wrong values. Constrained decoding removes the syntactic classes; schema validation detects the same classes and, with feedback, lets the model fix them at the cost of extra calls. Wrong values pass both: only domain checks, confirmation or downstream verification catch them.

Retries. If each attempt is valid with probability p, the chance of a valid call within r + 1 attempts is 1 − (1 − p)^(r+1); expected attempts are close to 1 + (1 − p) when p is high.

Tool selection. Choosing among m tools is a classification problem whose difficulty grows with m and with overlapping descriptions; the definitions also consume context. Retrieval narrows m, but its recall caps end-to-end accuracy: too few candidates miss the right tool, too many bring back the selection problem.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Errors that pass schema validation:
  2. 2. Valid within r + 1 attempts:
  3. 3. Tool retrieval's recall…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How should an application choose among many tools, and how much do validation and constrained decoding improve tool calls?

History.

  • T. Schick et al., “Toolformer: language models can teach themselves to use tools” (2023).
  • OpenAI function calling (June 2023); S. Patil et al., “Gorilla: large language model connected with massive APIs” (2023); Y. Qin et al., “ToolLLM” (2023).
  • Berkeley Function-Calling Leaderboard (2024) for evaluating tool calls.

Exercise 2. 200 tools, each described by 5 concept words (one of 2 synonyms each); 1000 tasks naming 3 concepts of the target tool.

  • Selection: the model picks the right tool among m offered with probability 0.98 − 0.0015m, an assumption meant to reflect the reported degradation with many tools. Candidates come from real idf-weighted word-overlap retrieval.
  • Arguments: free generation is malformed 4%, missing a field 7%, wrong type 5%, invalid enum 3% and well-formed but wrong 6% of the time. Validation sends errors back for up to 2 retries; constrained decoding prevents the first four.
tools offered retrieval recall right tool chosen description tokens
3 retrieved 0.710 0.692 450
10 retrieved 0.865 0.823 1500
all 200 1.000 0.674 30000
argument strategy fully correct calls calls per task
free generation 0.769 1.00
validate + retry 0.924 1.21
constrained decoding 0.929 1.00
  • Retrieving 10 tools beat offering all 200 by 15 points at a twentieth of the tokens. Three were too few: the right tool was missing 29% of the time.
  • Validation with feedback recovered almost all format errors at 21% more calls; constrained decoding matched it in one call.
  • Wrong values (6%) passed every check: they need domain validation or confirmation.
  • Seeds 1 and 2: 10 retrieved 0.856 and 0.848; validate + retry 0.909 and 0.936; constrained 0.939 and 0.934.
  • Caveat: the selection curve and error rates are assumptions; measure them for your model and tools.
🐍 Exercise 2 (research): how should an application choose among many tools, and how much do validation and constrained decoding improve tool calls?
Compare offering all tools with retrieving candidates, and free, validated and constrained tool-call generation.

Function calling in AI, robotics and aerospace

  • Robot task planning: a language model calls skills such as pick, place and navigate with typed parameters; validation checks reachability and limits before execution.
  • Operations assistants: read-only telemetry queries run freely; commands that change state require operator confirmation.
  • Engineering tools: models call simulators, solvers and databases rather than computing answers themselves.

References

  1. T. Schick et al. (2023). “Toolformer: language models can teach themselves to use tools.” NeurIPS.
  2. S. G. Patil, T. Zhang, X. Wang and J. E. Gonzalez (2023). “Gorilla: large language model connected with massive APIs.” arXiv:2305.15334.
  3. Y. Qin et al. (2024). “ToolLLM: facilitating large language models to master 16000+ real-world APIs.” ICLR.
  4. F. Yan et al. (2024). “Berkeley function calling leaderboard.” Gorilla project.