What function calling really is
Function calling is often described as the model "using a tool", which hides the important part: the model never executes anything. It produces a structured message saying which tool it wants and with what arguments. The application decides whether to run it, runs it with its own credentials, and returns the result. This separation is the whole safety model. The model is a planner that emits JSON; the runtime is the only component with authority. It also means function calling is not a special mode of inference. It is ordinary next-token prediction, shaped by training data and a schema in the prompt, until the output looks like a tool request rather than a sentence.
The request: tools are part of the prompt
A tool-enabled request adds a tools array to the usual messages. Each entry has a type, a name, a description and a JSON Schema for the arguments: {"type":"function","function":{"name":"get_order","description":"Look up an order by its ID. Use when the customer provides an order number.","parameters":{"type":"object","properties":{"order_id":{"type":"string","description":"Order ID such as ORD-4821"}},"required":["order_id"]}}}. The server renders these declarations into the prompt using the model's chat template. They are not magic configuration; they are text the model reads. That is why tool descriptions matter as much as function names, and why a hundred tools consume context and attention before the first user token is generated.
The response: a tool call, not an answer
When the model chooses a tool, the response message contains a tool_calls array and the finish reason is tool_calls. Each entry looks like {"id":"call_abc123","type":"function","function":{"name":"get_order","arguments":"{\"order_id\":\"ORD-4821\"}"}}. Notice that arguments is a JSON-encoded string, not an object. This is a common integration bug: the outer envelope is JSON, but the arguments must be parsed a second time. The id is assigned by the server or the client depending on the stack, and it exists so the matching result can be attached to the right call. The model may also return ordinary content alongside tool calls, which is usually a short explanation of what it is about to do and should not be treated as the final answer.
Tool choice is a runtime control, not a suggestion
The request can carry a tool_choice setting. With auto, the model decides whether to answer or call a tool. With none, tool schemas are still visible but the model must answer in prose, which is useful for a final synthesis pass. With required, the model must call at least one tool, which is how you force a lookup before an answer in a retrieval pipeline. A named function forces that specific tool, useful for a first routing step or for testing. These controls are enforced by the serving stack, not by the model's goodwill, but they only constrain the first move: a model told to call get_order can still choose nonsense arguments. Use required sparingly. If the model genuinely lacks the information to call anything, forcing a call produces invented arguments, which is worse than a refusal.
Why the structured contract replaced prompt parsing
Before tool APIs, applications asked the model to "respond with JSON like this" and parsed the text with a regular expression. It worked often enough to ship and failed in ways that were hard to reproduce: markdown fences around the JSON, a trailing comma, a friendly sentence before the object, or a nested quote that broke the parser. Tool calling moved the format into the protocol. The server knows which tokens belong to a call, the client receives a typed envelope, and the result can be attached to a specific id. The improvement is not that the model became smarter; it is that the interface became explicit and the failure modes became detectable. That is also why older open-weight models can appear bad at tools: they were trained to emit the right JSON in free text, not to use the protocol's envelope.
The round trip is stateless
The second request is where most confusion lives. You append the assistant message containing the tool_calls, then one message per call with role tool, the matching tool_call_id, and the result as content. You send the whole transcript back. The model does not remember the call; it reads the transcript as fresh input and decides what to do next. It might call another tool, call the same tool with corrected arguments, or produce the final answer. The loop ends when a response has content and no tool calls. Every iteration re-sends the system prompt, the tool schemas, the user request and all prior results, so token cost grows roughly quadratically with the number of steps unless the runtime compacts the history. A three-step task with a 3,000-token prefix and 500 tokens of new output per step bills roughly 10,500 input tokens, not 3,000, and the gap widens with every additional step.
How open-weight models learn the format
Base models do not know what a tool call is. Tool use is taught, usually in supervised fine-tuning on trajectories where a model receives a request, emits a call in a specific serialization, receives a result and continues. The training data fixes the exact syntax: which special tokens wrap the call, whether arguments are nested JSON or a Python-style expression, whether the tool name comes before or after the arguments. Different model families chose different conventions. Hermes models popularised a JSON object wrapped in tool_call tags; Llama 3.1 used a Pythonic call representation; Mistral used its own bracketed format; Qwen and others ship templates that resemble one of these. A model fine-tuned on one format will often produce something close but wrong when prompted with another.
Chat templates and tool parsers
Serving stacks therefore have two jobs. The chat template converts the OpenAI-style messages and tools into the exact text the model was trained on. The tool parser reads the model's raw output and converts it back into the structured tool_calls envelope. In vLLM you enable this with flags such as --enable-auto-tool-choice and --tool-call-parser hermes; SGLang exposes a similar parser option. If the parser does not match the model family, the symptoms are distinctive: the model writes a correct-looking call as plain text and the API returns it as content, or the arguments come back truncated or wrapped in extra prose. Always test one known tool call after deployment. A model that chats happily but never triggers a tool is usually a template or parser mismatch, not a reasoning failure.
Constrained decoding changes the reliability profile
Most servers can constrain generation to a grammar or JSON Schema, either for the whole response or only for the arguments field. vLLM exposes guided JSON and structured outputs; llama.cpp uses GBNF grammars; Outlines and XGrammar compile schemas into token masks. This eliminates malformed JSON and unknown fields, which removes a large class of retries. It does not guarantee that the values are correct or that the chosen tool is appropriate. A grammar can force a valid order ID format while the model invents an order that does not exist. Use constrained decoding for shape, validation and business rules for meaning, and keep both.
Designing tool schemas the model can use
- Name tools with a verb and an object: get_order, issue_refund, search_tickets. Avoid cute names and internal codenames.
- Write descriptions for selection, not documentation: state when to use the tool and when not to, including the neighbouring tool it is often confused with.
- Put every constraint you can into the schema: enums for status and category, formats for dates, minimum and maximum for amounts, required fields for anything non-optional.
- Keep arguments flat. Deeply nested objects increase malformed calls and make errors harder to explain back to the model.
- Return small, structured results. A tool that dumps a 40 KB API response burns context and hides the two fields that matter.
- Prefer several narrow tools over one tool with a mode parameter. The model selects between names more reliably than it constructs the right mode string.
- Cap the tool count. Beyond roughly twenty tools, selection accuracy drops and the schema overhead becomes material; retrieve or group tools by task instead.
- Version breaking changes in the name, such as search_v2, and keep the old tool until traces show no callers.
Validation, errors and repair
Treat every argument as untrusted input from a stochastic process. Parse the JSON, validate against the schema, check authorisation and business rules, then execute. When validation fails, return a tool message that states the problem precisely and how to fix it: "order_id must look like ORD-1234; the value '4821' is missing the prefix". Models correct themselves well from specific errors and poorly from generic ones. Cap repair attempts at two or three; beyond that, escalate or return a deterministic failure. Never silently coerce a bad value into a plausible one, because that converts a visible error into a wrong action. Distinguish transport errors, validation errors and business-rule rejections in the tool result so the model and your metrics can tell them apart.
Parallel calls and streaming
Modern models can emit several tool calls in one turn, for example looking up an order and a customer at the same time. Execute independent calls concurrently, then append all results before the next model pass; preserve the ids exactly. If one call fails, return a result for every id, including error results, or the transcript becomes invalid. Streaming adds a wrinkle: tool call deltas arrive in fragments, with an index identifying which call each fragment belongs to, and the arguments string may be split mid-token. Buffer by index and parse only when the stream finishes. Do not try to execute a partially streamed call unless your parser can prove the arguments are complete.
Security boundaries
Tool outputs are untrusted input. A web page, email or ticket comment can contain text that looks like instructions, and a model that treats it as such will happily call send_email with the attacker's content. Keep tool results in a clearly delimited data section, tell the model that content inside it is never an instruction, and still enforce policy outside the model. Scope credentials per tool and per user, prefer read-only tokens, allowlist destinations for network tools, never interpolate model output into a shell command, and require confirmation for writes. Log arguments and results with secrets redacted. The model should be able to do the task with the least privilege that makes it possible, and the runtime should refuse anything outside that envelope even when the model asks nicely.
Debugging and evaluation
Log the raw request and response for every step, not just the final answer. The most common defects are visible immediately: the tool schema was not rendered, the model chose a plausible but wrong tool, arguments were parsed from the wrong field, or the result was too large and got truncated. Build three metrics: tool selection accuracy on a labelled set, argument exact-match or field-level accuracy, and end-to-end task success. Track per-tool error rates and retry counts; a single tool with a 30 percent failure rate will dominate the agent's behaviour. Run evaluations at temperature zero for comparability, but also sample at production temperature to see the variance. Replay traces after prompt or model changes, because tool-use behaviour is sensitive to small wording differences.
Tool calling is not the only way to ground a model
Retrieval augments the prompt with facts but cannot act. A code interpreter gives flexible computation and data manipulation inside a sandbox, at the cost of a heavier runtime and a larger attack surface. A deterministic workflow hard-codes the sequence and uses the model only where judgement is needed. Function calling sits between them: structured enough to audit, flexible enough to let the model choose the path. Many production systems combine all four, using retrieval to supply context, tools for actions, code for calculation and a workflow for the parts that must happen in a fixed order.
A deployment checklist
- Confirm the model was trained for tool use and that its chat template includes the tools section.
- Match the serving stack's tool parser to the model family and test one call end to end.
- Validate arguments against the schema and against business rules before execution.
- Give every call an id, every write an idempotency key, and every tool a scoped credential.
- Cap steps, retries and tokens per task; return structured failure instead of looping.
- Log full trajectories with token counts, and build a small labelled evaluation set.
- Re-test after every model, template or parser upgrade; compatibility is not transitive.
Bottom line
Function calling is a serialization contract wrapped around ordinary inference. The model proposes, the runtime disposes. Reliability comes from matching the template and parser to the model, designing narrow schemas, validating everything and treating tool output as hostile. Get those four things right and a 7B open-weight model can drive real workflows; get them wrong and even a frontier model will look incompetent.