How LLM function calling and tool use work under the hood
Learn how LLMs invoke external tools via JSON Schema definitions, structured tool_calls tokens, host-side execution, and tool result injection.
An LLM is an autoregressive text predictor, not an execution runtime—it can’t query a database or call an HTTP endpoint on its own. This post breaks down how function calling bridges that gap, from injecting JSON Schema definitions to intercepting structured
tool_callstokens and feeding execution results back into the conversation.
Why LLMs need external tools
Even frontier language models share three structural limits because of how they’re trained and served:
- Knowledge cutoff: Weights freeze at training time, so the model can’t know live order statuses, current inventory, or anything published after training.
- No deterministic computation: A model predicts likely next tokens rather than running an ALU. Multi-step arithmetic, date math, and strict rule evaluation drift easily.
- No external side effects: A standalone model can’t send a Slack alert, update a database row, or trigger a refund.
Early integrations worked around this with prompt engineering—asking the model to emit text like Action: search[query] and parsing it with regular expressions. In practice, those parsers broke constantly on missing quotes, trailing commas, or unexpected prose wrapped around the payload.
Function calling (also called tool use) solves this at the model and API level. Instead of relying on fragile free-form text, the model is trained to emit structured tool invocation payloads when an external action is needed.
1
2
3
4
5
6
7
[Common misconception]
"The LLM connects directly to PostgreSQL and executes SQL." (False)
[What actually happens]
"The LLM reads a tool specification and outputs structured JSON asking the host
to run a specific function with specific arguments. The host application performs
all network calls, database queries, and side effects." (True)
The four-step tool calling feedback loop
Tool use isn’t a single API call. It’s a four-stage ping-pong loop between your host application and the model API.
flowchart TD
subgraph HostLayer ["1. Host Application"]
A["Receive user request"] --> B["Attach tool specs (JSON Schema)"]
B --> C["Send API request (Messages + Tools)"]
end
subgraph ModelLayer ["2. LLM Engine"]
C --> D{"Need a tool call?"}
D -->|"Plain text"| RES1["Generate final answer"]
D -->|"Call tool"| TC["Emit tool_calls JSON\n(finish_reason: tool_calls)"]
end
subgraph ExecLayer ["3. Runtime Execution"]
TC --> E["Intercept and deserialize args"]
E --> F["Run local method or external API"]
F --> G["Capture tool output"]
end
subgraph FeedbackLayer ["4. Result Injection"]
G --> H["Append tool result message"]
H --> I["Re-send history + tool result"]
I --> J["Synthesize grounded answer"]
end
RES1 --> K["Return to user"]
J --> K
The host application owns execution privileges at every step. The model only decides which tool to request and extracts the arguments from the conversation.
Defining tool specs and generating call tokens
Step 1: Injecting JSON Schema tool definitions
When I send a user prompt to the model, I attach the list of available tools formatted as JSON Schema (Draft 7 or 2020-12). The model relies on three fields to make its decision:
name: The unique identifier the host uses to route the call.description: When and why to invoke the tool.parameters: Expected types, formats, defaults, and required keys.
Here’s a complete tool definition for looking up a customer order and optional courier tracking data:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
"type": "function",
"function": {
"name": "lookup_customer_order",
"description": "Look up a customer order by orderId and return payment status, line items, and tracking info. Call this when the user asks about order status or delivery progress.",
"parameters": {
"type": "object",
"properties": {
"orderId": {
"type": "string",
"description": "Order identifier starting with ORD- (example: ORD-20251110-01)"
},
"includeTrackingDetails": {
"type": "boolean",
"description": "Whether to include live carrier hub location and transit events",
"default": false
}
},
"required": ["orderId"],
"additionalProperties": false
}
}
}
Treat
descriptionas part of your system prompt. The model never sees your Kotlin or Java source code, so vague descriptions trigger false-positive tool calls or malformed arguments. Always state when to call the tool and show the exact argument format.
Step 2: Structured tool_calls token generation
Suppose a user asks: "Where is my order ORD-20251110-01 right now?"
The model matches ORD-20251110-01 against orderId and infers that "where is ... right now" requires includeTrackingDetails: true. Instead of returning natural language in content, it leaves content as null, populates tool_calls, and sets finish_reason to "tool_calls".
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
{
"id": "chatcmpl-A1B2C3D4E5",
"object": "chat.completion",
"created": 1762743600,
"model": "gpt-4o",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_9x8w7v6u5t4s",
"type": "function",
"function": {
"name": "lookup_customer_order",
"arguments": "{\"orderId\":\"ORD-20251110-01\",\"includeTrackingDetails\":true}"
}
}
]
},
"finish_reason": "tool_calls"
}
]
}
Notice that arguments is a stringified JSON payload, not a nested JSON object. Because the model generates tokens sequentially, the API returns the raw JSON string that your host must deserialize and validate.
Executing tools on the host and injecting results
Step 3: Intercepting and dispatching on the host
When my Spring Boot service sees finish_reason == "tool_calls", it doesn’t return anything to the user yet. Instead, it looks up the handler by name, deserializes arguments into a typed DTO, and runs the business logic.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// src/main/kotlin/com/example/ai/tool/OrderToolDispatcher.kt
package com.example.ai.tool
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
data class OrderLookupArgs(
val orderId: String,
val includeTrackingDetails: Boolean = false
)
data class OrderLookupResult(
val orderId: String,
val status: String,
val items: List<String>,
val courier: String?,
val currentLocation: String?
)
@Component
class OrderToolDispatcher(
private val objectMapper: ObjectMapper,
private val orderService: OrderService
) {
private val log = LoggerFactory.getLogger(javaClass)
fun executeTool(toolName: String, argumentsJson: String): String {
log.info("Received tool execution request: name={}, args={}", toolName, argumentsJson)
return when (toolName) {
"lookup_customer_order" -> {
val args = objectMapper.readValue<OrderLookupArgs>(argumentsJson)
val result = orderService.findOrderDetails(args.orderId, args.includeTrackingDetails)
objectMapper.writeValueAsString(result)
}
else -> {
log.error("Unknown tool requested: {}", toolName)
throw IllegalArgumentException("Unsupported tool: $toolName")
}
}
}
}
Treat every argument coming from an LLM as untrusted user input. Prompt injection or hallucinated IDs can lead to unauthorized data access or malformed queries. Always enforce input validation and authorization checks inside your host service—never inside the prompt alone.
Step 4: Tool result injection and final synthesis
After executing orderService.findOrderDetails, I append a tool role message to the conversation history and send the full history back to the model.
The tool_call_id field must match the id from the assistant’s tool_calls entry one-to-one. Most LLM APIs reject the request with a 400 Bad Request if any tool_call_id is missing or mismatched.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
{
"model": "gpt-4o",
"messages": [
{
"role": "user",
"content": "Where is my order ORD-20251110-01 right now?"
},
{
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_9x8w7v6u5t4s",
"type": "function",
"function": {
"name": "lookup_customer_order",
"arguments": "{\"orderId\":\"ORD-20251110-01\",\"includeTrackingDetails\":true}"
}
}
]
},
{
"role": "tool",
"tool_call_id": "call_9x8w7v6u5t4s",
"content": "{\"orderId\":\"ORD-20251110-01\",\"status\":\"SHIPPING\",\"items\":[\"Ergonomic Keyboard\"],\"courier\":\"UPS\",\"currentLocation\":\"Louisville Hub - Arrived at Facility\"}"
}
]
}
With ground-truth data now sitting in its context window, the model synthesizes a clean response without guessing:
1
2
3
[Final model response]
"Your order ORD-20251110-01 (Ergonomic Keyboard) is currently in transit via UPS.
It arrived at the Louisville Hub facility and is moving on schedule."
Parallel tool calling and trade-offs
When a user asks for multiple independent lookups in one prompt—such as "Compare tomorrow's weather in Seoul and Tokyo"—modern models don’t waste two round-trips. They emit multiple entries in a single tool_calls array:
1
2
3
4
5
6
7
8
9
10
"tool_calls": [
{
"id": "call_weather_seoul_01",
"function": { "name": "get_weather", "arguments": "{\"city\":\"Seoul\"}" }
},
{
"id": "call_weather_tokyo_02",
"function": { "name": "get_weather", "arguments": "{\"city\":\"Tokyo\"}" }
}
]
On the host side, I dispatch these concurrently using CompletableFuture or Kotlin coroutines (async/awaitAll), then append both tool result messages before the second LLM call. That cuts network round-trips in half.
When not to use function calling
Tool calling adds latency (at least two LLM calls per turn) and token overhead (every attached JSON Schema consumes input tokens on every request). Don’t reach for it blindly:
| Scenario | Recommended approach | Why |
|---|---|---|
| Deterministic UI action (button click, form submit) | Direct REST / RPC call | No reason to pay LLM latency or risk wrong arguments |
| Static reference data needed on every turn | Inject directly into system/user context | Avoids an extra round-trip just to fetch predictable data |
| Dynamic lookup based on natural-language intent | Single-turn function calling | Model extracts parameters cleanly from free-form text |
| Multi-step tasks where step 2 depends on step 1 | ReAct agent loop | Single-turn calls can’t branch or recover from errors |
Production checklist and next steps
Function calling turns a text generator into a controlled interface over your backend systems, as long as you keep the boundaries clear:
- Validate every argument: Parse
argumentswith strict schemas (additionalProperties: false) and enforce tenant or user ownership checks in the host service. - Keep tool catalogs lean: Passing 40+ tool schemas inflates input token costs and degrades tool-selection accuracy. Scope tools per endpoint or workflow.
- Match
tool_call_idstrictly: Always pair every emittedtool_calls[i].idwith a correspondingtoolmessage, including structured error strings when a call fails. - Return concise payloads: Strip unused database columns before serializing tool outputs so you don’t bloat the context window.
Single-turn tool use handles direct lookups well, but it stops short when the model needs to inspect a tool’s output, decide on a follow-up action, or recover from a failed API call. That’s where multi-turn reasoning loops like the ReAct pattern come in.