Function Calling
🎯 Introduction
Suppose you ask an AI in an e-commerce admin panel, "How many units of SKU-A100 are in stock?" The model can explain inventory, but it does not know the stock in your business system. Your backend already has an inventory query function. How can the model use it to answer?
This is what Function Calling (also called Tool Calling) enables. Using AIHubMix + the OpenAI SDK, this article walks through an inventory query to declare a tool, read the model's call request, execute a local function, and return the result to the model. We cover one complete call here; later AI Agent courses cover repeated tool calls and task planning.
🧱 How Function Calling Works
Here is what happens between the program and model when a user asks about SKU-A100:
| Step | Handler | Action |
|---|---|---|
| 1 | Node.js | Tell the model the inventory tool's name, purpose, and parameter requirements |
| 2 | Model | Request a call to get_stock with SKU-A100 as the argument |
| 3 | Node.js | Validate the request and execute getStock("SKU-A100"), obtaining stock 18 |
| 4 | Node.js | Send the query result back as a tool message |
| 5 | Model | Answer from the result: "SKU-A100 currently has 18 units in stock." |
The model only requests a call; it does not run your JavaScript function directly. The Node.js backend decides whether to execute it, which function is allowed, and which arguments to pass.
This also explains why you typically need two model requests: the first produces a tool call; the second lets the model read the execution result and generate the final answer.
🛠 Declare an Inventory Query Tool
Continue with ai-sdk-course, using Node.js 24.x and openai@7.62.0, and reuse AI_API_KEY, AI_BASE_URL, and AI_MODEL from .env. Use a model that supports Chat Completions tool calls, such as the gpt-4o-mini used earlier. Actual availability depends on the capabilities currently offered by AIHubMix.
Create 06.function-calling.mjs in the project root and add the inventory function first:
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.AI_API_KEY,
baseURL: process.env.AI_BASE_URL
});
const stockTable = {
"SKU-A100": 18,
"SKU-B200": 0
};
function getStock(sku) {
if (!Object.hasOwn(stockTable, sku)) {
return { sku, found: false, stock: null };
}
return { sku, found: true, stock: stockTable[sku] };
}
Mock data replaces a database here so we can focus on tool calling. The result deliberately distinguishes zero stock (found: true, stock: 0) from a nonexistent product (found: false). These cases are different.
At this point, getStock() is an ordinary Node.js function unknown to the model. Declare the tool in the same file:
const tools = [
{
type: "function",
function: {
name: "get_stock",
description: "Look up the current stock quantity for a product SKU",
parameters: {
type: "object",
properties: {
sku: {
type: "string",
description: "Product identifier, for example SKU-A100"
}
},
required: ["sku"],
additionalProperties: false
},
strict: true
}
}
];
This does not send the code of getStock() to the model. It supplies instructions for calling a tool:
name: The tool name visible to the model,get_stock, which is distinct from the JavaScript functiongetStock().description: Explains that the tool queries inventory.parameters: Declares the required arguments; this example needs onlysku.
The previous lesson introduced JSON Schema, so we will not repeat properties, required, and related syntax. Previously, the schema constrained generated data; here, it describes arguments for a tool call. strict: true asks the model to follow the declared argument structure strictly, but the backend must still validate actual arguments.
🛠 Ask the Model to Request a Tool Call
Append this to the same file:
const messages = [
{
role: "system",
content: "Always use the tool to look up inventory. Answer from the query result; do not invent quantities if the product does not exist."
},
{
role: "user",
content: "How many units of SKU-A100 are in stock?"
}
];
const first = await client.chat.completions.create({
model: process.env.AI_MODEL,
messages,
tools,
tool_choice: "required",
parallel_tool_calls: false
});
const assistantMessage = first.choices[0]?.message;
const calls = assistantMessage?.tool_calls ?? [];
if (calls.length !== 1 || calls[0].type !== "function" ||
calls[0].function.name !== "get_stock") {
throw new Error("The model did not return the expected inventory query request");
}
const call = calls[0];
console.log("Model tool request:", JSON.stringify(call, null, 4));
This first demonstration provides only one tool and uses two settings to control calling behavior:
tool_choice: "required": Requires a tool call instead of a direct text answer.parallel_tool_calls: false: Disables parallel tool calls so this example handles a single call request.
Both settings require support from the selected model and AIHubMix's API. Checking calls.length provides a clear error if the response differs from expectations, rather than letting subsequent code process unsuitable data.
What Does the Model Return?
The model may return the following tool_calls (other response fields are omitted and the call ID is illustrative):
{
"id": "call_abc123",
"type": "function",
"function": {
"name": "get_stock",
"arguments": "{\"sku\":\"SKU-A100\"}"
}
}
This data is not the inventory result. It is the model's call request:
| Field | Meaning |
|---|---|
function.name | The tool the model wants to use: get_stock |
function.arguments | Arguments supplied by the model as a JSON string |
id | Identifier for this tool call, needed when returning the result |
The inventory function has not run yet. The model knows it needs to query SKU-A100, but does not know its stock is 18.
🛠 Execute the Function and Return Its Result
Only after receiving the tool call request does Node.js perform the inventory query. Append this to the same file:
const args = JSON.parse(call.function.arguments);
if (typeof args?.sku !== "string" || !/^SKU-[A-Z]\d{3}$/.test(args.sku)) {
throw new Error("Invalid SKU argument; execution refused");
}
const result = getStock(args.sku);
console.log("Backend query result:", result);
// Preserve the model's tool call, then append its corresponding execution result
messages.push(assistantMessage);
messages.push({
role: "tool",
tool_call_id: call.id,
content: JSON.stringify(result)
});
const second = await client.chat.completions.create({
model: process.env.AI_MODEL,
messages
});
console.log("Final model answer:", second.choices[0]?.message?.content ?? "no text returned");
First parse function.arguments, validate sku against this example's product identifier rules, and then call getStock(). Invalid arguments are rejected. Backend validation remains necessary even with strict enabled in the tool declaration.
For SKU-A100, the function returns:
{
"sku": "SKU-A100",
"found": true,
"stock": 18
}
Now comes the key step: put the tool result into messages and send a second model request.
| Message role | Message contents |
|---|---|
user | How many units of SKU-A100 are in stock? |
assistant | The model requests get_stock, including the call ID and arguments |
tool | Node.js returns the query result for that call: 18 units |
assistant | The model forms a final answer from the query result |
The multi-turn conversation article showed how messages preserves context. This article adds tool call messages:
messages.push(assistantMessage)preserves the model's call request.role: "tool"identifies a tool execution result, rather than a new user question.tool_call_id: call.idassociates the result with the correct earlier call.
Do not disguise inventory results as new user messages. The second request needs both the tool the model requested and the data the backend returned. This example omits tools in the second request so the model only formulates an answer from the query result.
Run the Complete Example
Put all four JavaScript blocks above in 06.function-calling.mjs, save it, and run from the project root:
node --env-file=.env 06.function-calling.mjs
If you need the local proxy verified earlier:
HTTPS_PROXY=http://127.0.0.1:7890 NODE_USE_ENV_PROXY=1 node --env-file=.env 06.function-calling.mjs
The terminal might display the following (illustrative only; call IDs and model answers vary):
Model tool request: {
"id": "call_abc123",
"type": "function",
"function": {
"name": "get_stock",
"arguments": "{\"sku\":\"SKU-A100\"}"
}
}
Backend query result: { sku: 'SKU-A100', found: true, stock: 18 }
Final model answer: SKU-A100 currently has 18 units in stock.
The output shows that the first model request produces a tool call, Node.js executes the inventory function, and the second model request uses the result to generate an answer. The function execution between model requests is the main difference between function calling and ordinary text generation.
🪤 Handle Other Outcomes
After completing the normal flow, consider these cases that an application must distinguish:
| Situation | Handling in this example |
|---|---|
| Model does not return the required tool call | Throw an error; do not mistake model text for live inventory |
Tool name is not the allowed get_stock | Refuse execution |
| Arguments are invalid JSON or the SKU format is wrong | Parsing fails or execution is refused; no inventory query runs |
| SKU format is valid but the product does not exist | Query normally and return found: false, rather than stock 0 |
Model or platform does not support required, parallel_tool_calls, or strict | Check model capabilities and error details, then adjust parameters to match support |
By default, tool_choice: "auto" lets the model decide whether to call a tool; "none" prohibits tool use. This example uses "required" to demonstrate the full flow. Applications that let the model choose must still handle responses without tool calls.
⚖️ Function Calling and Structured Output
The previous lesson, Structured Output, organized supplied information into a specified structure. Function calling asks the application to execute a capability.
| Requirement | Better approach |
|---|---|
| Extract names and prices from product descriptions | Structured output |
| Query live stock in an inventory system | Function calling |
Both can use JSON Schema, but for different purposes: one constrains the final data, while the other constrains tool arguments.
❓ Knowledge Check
Q1: Why ask the model to generate another answer after querying inventory?
The tool returns structured business data, which the model can turn into a natural-language reply suited to the question. If the page only needs a stock number, you can use the backend result directly without a second model request.
Q2: Why must a tool message include tool_call_id?
A model can request multiple tool calls in one request. The call ID identifies which call a result belongs to, preventing results from different tools from getting mixed up. This article demonstrates one tool call; later lessons cover repeated execution and orchestration.
🧪 Exercise
- Add
"SKU-C300": 42tostockTableand ask the model about this product. Verify that the tool arguments, function result, and final answer agree. - Ask about
SKU-D400, which has a valid format but is absent from the inventory table. Observefound: falseand confirm the model does not confuse "product not found" with "zero stock". - Change
tool_choiceto"auto", observe whether the model still calls the inventory tool, and explain why an application cannot assume every response containstool_calls.
Success criteria: Identify where the model only requests a call, where Node.js actually executes the function, and why the assistant tool call message must correspond to the tool result message.
🎉 You have completed the full flow: the model requests a tool, the backend executes a function, and the model uses the result to answer the user.
