Tool Calling is a pattern that lets an LLM invoke external functions, APIs, or services during generation. The model outputs a structured function call with arguments, the system executes it, and the result is fed back to the model for the next reasoning step.
At a Glance
- Problem: A language model on its own cannot reach outside its prompt and training data, so it cannot check live data, look up a customer record, compute precisely, or trigger an action the user expects to actually happen.
- Forces: The model needs enough tools to act, but large tool sets cause wrong-tool selection; letting the model fetch context on demand keeps prompts small, but every call adds latency; more capable tools widen the blast radius of a bad call.
- Solution: Describe each tool with a name, a description, and a parameter schema. The model emits a structured call; your code validates the arguments, executes the function, and returns the result for the model's next step.
- Consequences: Gains: access to current data and external actions, with your code keeping full control over what runs. Costs: added latency per call, ongoing schema maintenance as APIs change, and a security surface that grows with tool power.
What problem does Tool Calling solve?
On its own, a language model generates text from its training data and whatever context you put in the prompt, and it cannot reach outside that boundary. It cannot call an API to check the weather or query a database for a customer record. Its arithmetic is only as precise as token prediction can simulate. It cannot send an email, create a calendar event, or trigger a deployment.
That rules out raw LLMs for most practical applications, because users expect the system to do the thing rather than describe how to do it. The gap between "I can tell you how to check your account balance" and "I checked your account balance and it is $1,247.30" is the gap between a chatbot and a useful agent, and tool calling closes it.
How does Tool Calling work?
The pattern works through a structured loop between your application code and the language model. You define a set of tools, each described by a name, a natural language description of what it does, and a schema for its input parameters. You include these tool definitions in the system prompt or API configuration when calling the model.
When the model decides it needs to use a tool, it does not generate a natural language response. Instead, it emits a structured object, typically JSON, specifying which tool to call and what arguments to pass. Your application code intercepts this, validates the arguments, executes the actual function (makes the API call, runs the database query, performs the calculation), and returns the result to the model. The model then uses that result to formulate its response to the user.
This loop can repeat multiple times within a single conversation turn. The model might call a search tool, examine the results, decide it needs more specific information, call a different tool with refined parameters, and then synthesize a final answer from all the gathered data. Each iteration follows the same pattern: model emits a tool call, your code executes it, the result goes back to the model.
The model never executes anything itself. It produces a description of what it wants to happen, and your code, as the execution layer, keeps full control over what actually runs. Before any action happens you can validate inputs, enforce rate limits, check permissions, and log it. The model proposes and your code decides.
When should you use Tool Calling?
Tool calling is the right pattern whenever the model needs information or capabilities that are not in its training data or the current prompt context. The most common cases are real-time data access (current stock prices, live system status, weather), operations on external systems (sending messages, updating records, triggering workflows), and precise computation (math, date calculations, data transformations where token prediction is unreliable).
It is also the right choice when you want to keep the model's responsibilities narrow. Rather than trying to stuff every possible piece of context into the prompt, you let the model decide what information it needs and fetch it on demand. This keeps prompts small, reduces token costs, and means the model works with current data rather than a potentially stale context snapshot.
If you are building anything that goes beyond question-answering over static text, you will likely need tool calling. It is the foundation of agent-style systems where the model acts as a reasoning and planning layer while external tools handle execution.
When not to use it: when the answer lies in a static document collection, Basic RAG retrieves it without the model deciding when to call anything. When the work is multi-step computation or data manipulation, Code Execution handles it in one sandboxed run instead of a long chain of tool calls. Avoid exposing a large catalog of similar tools in one context, since selection quality drops; narrow the set per conversation or route first with a Semantic Router.
Implementation
Worked Example: Cost and Latency
A support assistant answers 10,000 order-status questions a day on the large model.
| Setup | Calls per request | Tokens per request (in / out) | Cost per 1,000 requests | Latency per request |
|---|---|---|---|---|
| No tools: full account history pasted into the prompt | 1 | 8,000 / 250 | $27.75 | 4.7 s |
| Tool Calling: model fetches the one order it needs | 2 | 3,450 / 300 | $14.85 | 6.2 s |
Assumptions: the pasted history is 6,500 tokens on top of a 1,500-token prompt. With tools, the 1,500-token prompt (tool schemas included) produces a 50-token call, the lookup returns 400 tokens and takes an assumed 0.2 s, and the second call writes a 250-token answer.
Without tools, 8,000 input tokens × $3.00 per million = $0.024 and 250 output tokens × $15.00 per million = $0.00375, so $27.75 per 1,000 requests. With tools, the two calls read 1,500 + 1,950 = 3,450 tokens ($0.01035) and write 300 ($0.0045), so $14.85. Latency is (0.5 + 50 / 60) + 0.2 + (0.5 + 250 / 60) ≈ 6.2 s against 0.5 + 250 / 60 ≈ 4.7 s. At 10,000 questions a day that is $148.50 instead of $277.50.
Tool Calling wins on cost whenever the context you would otherwise paste is much larger than what one lookup returns; it costs about 1.5 s per extra round trip, so a small, stable context is cheaper and faster to include directly.
What are the common pitfalls?
Schema design is where most tool-calling implementations fail first. If the tool description is vague or the parameter names are ambiguous, the model will misinterpret when to use the tool or what arguments to pass. A tool called "search" with a parameter called "query" gives the model very little to work with. A tool called "search_customer_orders" with parameters "customer_id" (required, string) and "date_range" (optional, object with start and end) communicates intent much more clearly. Time spent on precise, well-documented tool schemas shows up right away as fewer bad calls.
The model calling the wrong tool is a real problem in systems with many tools. If you expose 30 tools, the model may confuse similar-sounding options or try to use a tool for a purpose it was not designed for. Keeping the tool set small and focused for each conversation context helps. You do not need to expose every tool in every interaction.
Infinite loops happen when the model calls a tool, receives a result it does not understand or cannot use, and calls the same tool again with slightly different parameters, over and over. Setting a maximum tool call count per turn and implementing circuit breakers are basic safeguards.
Silent truncation does more damage per line of code than any other tool-design mistake. A search tool that returns the first 100 of 4,000 matches without saying it cut anything leaves the model believing there are only 100, and every decision downstream inherits that wrong number. Three fixes travel together. Disclose that you truncated and by how much. When you must cap, sample across the whole result set rather than taking whichever entries happen to sort first, so the model sees a representative slice instead of an alphabetical accident. And write the full result somewhere the model can reach, such as a file path it can read or grep, so the cap becomes a summary rather than a wall. The same discipline generalizes to any oversized output: replace the inline result with a bounded preview plus a locator and a hint describing how to retrieve the rest.
Error messages that do not say whether retrying will help are the other quiet failure. When a sandbox or policy layer blocks an operation, a bare "permission denied" invites the model to try four more spellings of the same command. Stating that the refusal is a deliberate policy decision rather than a malformed call, and that rewriting the command will not change the outcome, ends the detour in a single turn. Sort your failures into the ones worth retrying (transient errors, rate limits, malformed input the model can correct) and the ones that never are, such as policy denials, missing capabilities, and revoked credentials. Then make the tool result say which kind it is.
Security is the most serious concern, because the model generates inputs that your code executes. If one of your tools writes to a database or calls a third-party API with side effects, a malicious or confused model could cause real damage. Every tool call should be validated against an allowlist of permitted operations, parameter values should be sanitized, and destructive operations should require explicit confirmation before execution.
What are the trade-offs?
Each tool call adds latency. The model must generate the structured output, your code must execute the function, and the result must be sent back. For simple tools like a calculator, this overhead is small. For tools that call external APIs with their own latency (database queries, third-party services), each tool call can add hundreds of milliseconds or more. Multi-step tool chains where the model calls three or four tools in sequence can push total response time well beyond what feels interactive.
Schema maintenance is an ongoing burden. Every time you change an API, add a parameter, or rename a field, the tool schema must be updated. If the schema drifts from the actual implementation, the model will generate calls that fail at execution time. Treating tool schemas as a contract with the same discipline you apply to API versioning helps, but it is additional work that teams often underestimate.
The security surface area is real and proportional to the power of your tools. A read-only search tool is low risk. A tool that can modify production data is high risk. Work out the blast radius of every tool you expose and put guardrails on each one, scaled to its risk. Guardrails are not optional. Models will occasionally generate unexpected tool calls, and your execution layer has to handle them safely.
Goes Well With
Basic RAG can be reimplemented as a tool. Instead of hardcoding the retrieval step into your pipeline, you define a "search_documents" tool and let the model decide when to retrieve information and what queries to run. This gives the model more flexibility, as it can rephrase queries, search multiple times, or decide that retrieval is not needed for a particular question.
Code Execution pairs naturally with tool calling for tasks that require complex computation. Rather than trying to define a tool for every possible calculation, you expose a code execution sandbox as a single tool. The model writes and runs code to solve math problems, transform data, or generate visualizations. One sandbox covers far more cases than a fixed set of function tools, though it brings its own sandboxing security concerns.
References
- Schick, T., et al. (2023). Toolformer: Language Models Can Teach Themselves to Use Tools. NeurIPS 2023. arXiv
- Patil, S., et al. (2024). Gorilla: Large Language Model Connected with Massive APIs. NeurIPS 2024. arXiv
Further Reading
- DeepSeek Harness, tool-output spill policy. Replaces an oversized tool result with a bounded head/tail preview plus the stored locator and a retrieval hint, keeping truncation both disclosed and recoverable. GitHub
- Schick et al., "Toolformer: Language Models Can Teach Themselves to Use Tools" (2023). Demonstrates that language models can learn to decide when and how to call external tools (calculators, search engines, translators) by training on self-generated tool-use examples. arXiv:2302.04761