Tool Use and Function Calling

Tool use and function calling is the capability that allows large language models (LLMs) to invoke external functions, APIs, and services during inference — bridging the gap between static text generation and dynamic interaction with the real world. It matters because it transforms LLMs from read-only knowledge retrieval systems into active agents that can fetch live data, run computations, and trigger side effects. The counterintuitive fact: the model never actually executes any code itself — it only outputs a structured description of what it wants to call, and an external orchestrator does the real work.

The core insight

An LLM with tool use doesn't run your Python functions — it decides which function to call and what arguments to pass, then hands that decision back to your application as structured data (usually JSON). Your code reads that JSON, actually calls the function, and feeds the result back into the conversation. The "aha moment" is realizing the LLM is acting like a very smart dispatcher: it reads a menu of available tools, figures out which tool fits the user's request, fills in the order form, and waits for the kitchen to cook the meal.

How It Works

Function calling works through a structured conversation loop. The model is given a list of tool schemas — descriptions of what each function does, what parameters it takes, and what types those parameters are. When the model decides a tool is needed, it emits a special response instead of plain prose. The decision loop can be described simply. At each step, the model scores whether to answer directly or invoke a tool:

1
a^=arg⁡max⁡a∈A  P(a∣x,T)\quad \hat{a} = \arg\max_{a \in \mathcal{A}} \; P(a \mid x, \mathcal{T})

Explanation: The model picks the action â (either "respond in text" or "call tool T with args") that has the highest probability given the user input x and the set of available tools 𝒯. Here, A\mathcal{A} is the set of all possible actions (one per tool plus the "just talk" option), xx is the conversation so far, and T\mathcal{T} is the tool schema list injected into the system prompt or a dedicated API field. After a tool is called and the result is returned, the model computes its next response conditioning on the augmented context:

2
P(y∣x,tcall,rresult)\quad P(y \mid x, t_{\text{call}}, r_{\text{result}})

Explanation: The final reply y is generated using not just the original input x, but also the tool call that was made and the result that came back. Here tcallt_{\text{call}} is the tool invocation (function name + arguments) and rresultr_{\text{result}} is the tool's return value, both appended as new messages before the model generates its answer. Here is the fundamental orchestration loop in Python: ```python import json import openai client = openai.OpenAI()

# 1. Define the tool schema tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current temperature for a city.", "parameters": { "type": "object", "properties": { "city": { "type": "string", "description": "The city name, e.g. 'London'" } }, "required": ["city"] } } } ]

# 2. The actual Python function the model wants to call def get_weather(city: str) -> dict:

# In a real app this would call a weather API return {"city": city, "temperature_c": 18, "condition": "Cloudy"}

# 3. First model call — model may request a tool messages = [{"role": "user", "content": "What's the weather in Paris?"}] response = client.chat.completions.create( model="gpt-4o", messages=messages, tools=tools, tool_choice="auto" # model decides whether to call a tool ) msg = response.choices[0].message

# 4. Check if the model wants to call a tool if msg.tool_calls: tool_call = msg.tool_calls[0] func_name = tool_call.function.name # "get_weather" func_args = json.loads(tool_call.function.arguments) # {"city": "Paris"}

# 5. WE run the function — not the model result = get_weather(**func_args)

# 6. Feed the result back as a new message messages.append(msg) # assistant's tool-call request messages.append({ "role": "tool", "tool_call_id": tool_call.id, "content": json.dumps(result) })

# 7. Second model call — now model has the data and writes a response final = client.chat.completions.create( model="gpt-4o", messages=messages, tools=tools ) print(final.choices[0].message.content)

# → "It's currently 18°C and cloudy in Paris." ``` A key structural piece is the tool schema — a JSON Schema object telling the model exactly what shape the arguments must take: ```python

# Richer schema example with multiple parameters and types weather_schema = { "name": "get_forecast", "description": "Get a multi-day weather forecast for a location.", "parameters": { "type": "object", "properties": { "city": {"type": "string"}, "days": {"type": "integer", "minimum": 1, "maximum": 7}, "units": {"type": "string", "enum": ["celsius", "fahrenheit"]} }, "required": ["city", "days"] } } ``` When multiple tools are available, the model can call them sequentially (one at a time, waiting for results) or — in systems that support it — in parallel, batching several tool calls in one response: ```python

# Parallel tool calls — model returns a list of tool_calls for tool_call in msg.tool_calls: # iterate over all requested calls name = tool_call.function.name args = json.loads(tool_call.function.arguments) result = dispatch(name, args) # your router function messages.append({ "role": "tool", "tool_call_id": tool_call.id, "content": json.dumps(result) }) ```

researcher · Jason Wei | b. 1997 | Chain-of-Thought and Emergent Capabilities

Jason Wei is a researcher at OpenAI (formerly Google Brain) who co-authored the landmark chain-of-thought prompting paper (2022) and the seminal "Emergent Abilities of Large Language Models" paper. His work on reasoning traces laid conceptual groundwork for understanding why large models can plan multi-step tool use sequences rather than just single calls. Surprisingly, Wei started his PhD program but left before completing it to join Google Brain as a full-time researcher — one of the most consequential early-career pivots in recent AI history.

Figure
Tool Use Orchestration Loop
User prompt LLM + tool schemas in system prompt tool_call JSON Orchestrator your Python code dispatch(name, args) call External Tool / API result tool result message final reply Tool Use Orchestration Loop LLM outputs JSON requests — your code executes the actual calls 1 2 3 4 5 6

Intuition

The Mental Model

Imagine you're a brilliant analyst who has never left the office and can only communicate by reading and writing memos. A colleague asks you: "What flights are available from New York to Tokyo next Friday?" You can't browse the internet yourself, but you can write a perfectly structured request slip and slide it under the door: `{"tool": "flight_search", "origin": "JFK", "destination": "NRT", "date": "2025-08-01"}`. Someone outside your office runs the search, writes the results on a new memo, and slides it back. You then read that memo and write a beautiful, conversational answer for your colleague. That's exactly what an LLM does with tool use — it writes the request slip (JSON), you run the search, and it writes the final answer. The model's entire contribution is deciding what to ask for and how to present the answer — the actual work of fetching information happens entirely outside it.

Historical Development

Origins · 1 minhow this was discovered
History
2021: WebGPT (OpenAI) — first major demonstration of an LM using a tool (Bing search) to answer questions, showing retrieval-augmented generation was viable at scale.
2022: ReAct framework (Yao et al., Google) — introduced "Reason + Act" prompting where models interleave chain-of-thought reasoning with tool calls, establishing the foundational agentic loop pattern.
2022: Toolformer (Schick et al., Meta AI) — trained a model to self-annotate its own training data with tool calls, showing function calling could be learned rather than only prompted.
2023 March: OpenAI releases ChatGPT Plugins — first widely-deployed consumer product built on structured function calling, giving LLMs access to third-party APIs like Wolfram Alpha and Expedia.
2023 June: OpenAI adds the `functions` parameter to the Chat Completions API — formalizing structured JSON function calling as an official API primitive and sparking widespread adoption.
2023 October: LangChain and LlamaIndex frameworks mature their tool/agent abstractions, enabling Python developers to compose multi-tool agents with a few dozen lines of code.
2024 April: OpenAI updates the API to replace `functions` with `tools` and adds parallel tool calling — allowing a single model response to request multiple function calls simultaneously.
2024: Anthropic (Claude), Google (Gemini), Mistral, and Llama 3 all ship first-class tool-use APIs, making function calling a standard cross-provider capability rather than an OpenAI exclusive.
2024–2025: Model Context Protocol (MCP) by Anthropic proposes a universal standard for how any LLM agent connects to any tool server, aiming to decouple tool definitions from specific model APIs.

Why It Matters

Real-World Impact
ChatGPT Code Interpreter (Advanced Data Analysis)Uses function calling to invoke a sandboxed Python kernel — the model emits code execution requests, the sandbox runs them, and results (including plots) are returned to the model as tool outputs, enabling genuine data analysis.
GitHub Copilot WorkspaceCalls tools for `read_file`, `write_file`, `run_tests`, and `search_codebase`, allowing the model to iteratively edit a real repository across multiple agentic steps rather than generating one-shot completions.
Retrieval-Augmented Generation (RAG) pipelinesThe retrieval step is implemented as a tool call — the model decides when to search (rather than always searching), what query to use, and how many results to fetch, making retrieval a dynamic model decision rather than a fixed preprocessing step.
Customer service agents (e.g., Intercom Fin, Salesforce Einstein)LLMs call tools like `lookup_order(order_id)`, `issue_refund(amount)`, and `update_ticket_status(status)` to take real actions in CRM systems, completing support flows end-to-end without human handoff.
OpenAI Assistants API with file searchFile search is exposed as a built-in tool that the model calls automatically when it decides the user's question requires looking inside uploaded documents, combining tool use with vector search under the hood.
LangChain / LangGraph multi-agent systemsIndividual agents are wired together by having each agent's "call a sub-agent" action implemented as a tool call, making the entire multi-agent coordination mechanism a generalization of single-tool function calling.
Perplexity AI web searchEvery user query triggers a model decision about whether and what to search; the search tool is called with a model-generated query string, results are fetched, and the model synthesizes a cited answer — a live production example of the ReAct loop at scale.

Prerequisites

What This Leads To

See Also

AI Agents and Agentic Loops · Retrieval-Augmented Generation · Prompt Engineering · Chain-of-Thought Prompting · Multi-Agent Frameworks

Before this

Where this leads