Priya already keeps official fee balances in a register at Shree Vidya Tuition Centre. She can call a chat API from Node.js and ask the model to draft a parent reminder, but she must not let the model invent the rupee amount. The safer pattern is function calling (also called tools): the model can ask your JavaScript to look the figure up; your code returns the official number; then the model writes the prose.
This lesson shows how to send an OpenAI-compatible tools list with fetch from Node.js, read choices[0].message.tool_calls, run a local get_fee_balance function, and send the result back as a tool message. The API key stays in an environment variable, never in the browser. We will not hardcode a key, and we will not let the model invent the balance.
Key takeaways
- Add a
toolsarray to the chat request so the model can ask your code to run a named function. - When the model wants a lookup, the arguments are usually at
choices[0].message.tool_calls[0].function.arguments— a JSON string you must parse and check. - Your JavaScript reads the official register. The model only sees the amount after you send it back.
- Return the result in a message with
role: "tool"and the sametool_call_id, then call the API once more for the finished text. - Keep
AI_API_KEYin the Node.js environment, never in front-end JavaScript.
What function calling changes
A plain chat call only has model and messages. The model then has to guess, or you have to paste the whole register into the prompt. Function calling adds a list of tools the model may request. You still POST to {base url}/v1/chat/completions.
{
"model": "gpt-4o-mini",
"messages": [
{
"role": "system",
"content": "You write short, polite messages for a tuition centre in India. Use get_fee_balance to look up official amounts. Never invent a rupee figure."
},
{
"role": "user",
"content": "What is Ananya Sharma's balance for November tuition? Write a 2-sentence reminder."
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_fee_balance",
"description": "Look up the official tuition balance in rupees for a student and month.",
"parameters": {
"type": "object",
"properties": {
"student": { "type": "string" },
"month": { "type": "string" }
},
"required": ["student", "month"]
}
}
}
]
}
If the model needs the balance, the reply is not yet a reminder. choices[0].finish_reason is often tool_calls, and the message includes a tool_calls list. The arguments arrive as a string of JSON, not as an already-parsed object:
{
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_abc123",
"type": "function",
"function": {
"name": "get_fee_balance",
"arguments": "{\"student\":\"Ananya Sharma\",\"month\":\"November\"}"
}
}
]
}
Look up the amount in your own code
The model does not have access to Priya’s register. You do. Keep official balances in a structure you control, and reject a name or month you do not know:
const DEFAULT_REGISTER = {
'Ananya Sharma|November': 1200,
'Rahul Iyer|November': 2450,
};
function getFeeBalance(args, register = DEFAULT_REGISTER) {
const student = args && args.student;
const month = args && args.month;
if (typeof student !== 'string' || student.trim() === '' || typeof month !== 'string' || month.trim() === '') {
throw new Error('get_fee_balance requires student and month strings.');
}
const key = `${student.trim()}|${month.trim()}`;
if (!Object.prototype.hasOwnProperty.call(register, key)) {
throw new Error('No official balance for that student and month.');
}
return { amount_inr: register[key] };
}
function parseToolArguments(argString) {
let parsed;
try {
parsed = JSON.parse(argString);
} catch {
throw new Error('The model did not return valid JSON arguments.');
}
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
throw new Error('Tool arguments must be a JSON object.');
}
return parsed;
}
Parse the arguments, then call getFeeBalance. If the model asks for a student who is not in the register, throw. Do not invent a number to keep the conversation going.
Send the result back and get the reminder
Append the assistant message (including tool_calls) and a tool message that carries the official amount. Use the same tool_call_id. Then call the API again. The second reply should be ordinary text at choices[0].message.content.
function firstToolCall(message) {
const calls = message && message.tool_calls;
if (!Array.isArray(calls) || calls.length === 0) {
return null;
}
return calls[0];
}
async function draftReminderWithTools(input, env = process.env, register = DEFAULT_REGISTER) {
const apiKey = apiKeyFromEnv('AI_API_KEY', env);
const baseUrl = env.AI_API_BASE || 'https://api.openai.com';
const model = env.AI_MODEL || 'gpt-4o-mini';
const messages = [
{
role: 'system',
content: 'You write short, polite messages for a tuition centre in India. Use get_fee_balance to look up official amounts. Use rupees when mentioning fees. Never invent a rupee figure.',
},
{
role: 'user',
content: `What is ${input.student}'s balance for ${input.month} tuition? Write a 2-sentence reminder.`,
},
];
const first = await callChatCompletions(baseUrl, apiKey, { model, messages, tools: FEE_TOOLS });
const toolCall = firstToolCall(first.message);
if (!toolCall) {
throw new Error('The model did not request a tool call.');
}
if (!toolCall.function || toolCall.function.name !== 'get_fee_balance') {
throw new Error('Unknown tool: ' + (toolCall.function && toolCall.function.name));
}
const result = getFeeBalance(parseToolArguments(toolCall.function.arguments), register);
messages.push({
role: 'assistant',
content: first.message.content ?? null,
tool_calls: first.message.tool_calls,
});
messages.push({
role: 'tool',
tool_call_id: toolCall.id,
content: JSON.stringify(result),
});
const second = await callChatCompletions(baseUrl, apiKey, { model, messages, tools: FEE_TOOLS });
const text = second.message && second.message.content;
if (typeof text !== 'string' || text === '') {
throw new Error('The API response had no message content.');
}
return { content: text, amount_inr: result.amount_inr };
}
callChatCompletions is the same kind of fetch helper as in the earlier JavaScript lesson: read AI_API_KEY from the environment, POST JSON, apply a timeout, and treat a non-2xx status or invalid JSON as an error. Return the whole message object this time, not only the content string, because you need tool_calls.
This lesson does one lookup and one follow-up call. That is enough for a reminder. A later agent-style loop can run more than one tool, but you should still cap the number of rounds so a bug cannot bill you for a tight loop.
The page in the office still must not hold the key. The browser can post the student name and month to your own Node.js server, as in the earlier lesson; the server runs draftReminderWithTools and returns only the reminder text.
Try this
First run the script without setting AI_API_KEY. You should get the missing-key error, not a network request. Then point AI_API_BASE at a local mock, or at a real compatible endpoint if you already have an account. Call getFeeBalance with Rahul Iyer and November; you should get amount_inr 2450 from the register, not from the model. If you run the full two-step call, confirm that the finished reminder mentions ₹2,450 and does not invent a different amount.
How this was tested
On Node.js 24, an empty AI_API_KEY raised the missing-key error, getFeeBalance returned 1200 for Ananya Sharma in November and rejected an unknown student, and parseToolArguments rejected invalid JSON. The two-step fetch flow was pointed at a local mock of POST /v1/chat/completions: a matching Bearer token first returned a get_fee_balance tool call, then a reminder that mentioned ₹1,200 (and ₹2,450 for Rahul Iyer); a wrong token returned HTTP 401 and the function threw API error: Invalid API key. No paid API was called here, so run one live call against your own provider before you rely on it.
What you learned
- Function calling lets the model request a named tool; your Node.js code runs it and sends the result back.
- Tool arguments arrive as a JSON string on
choices[0].message.tool_calls[0].function.arguments. Parse and validate them. - Official amounts come from your register (for example ₹1,200), never from a guess in the model’s first message.
- After the tool result, a second chat call produces the reminder text. Keep
AI_API_KEYin the environment, off the front end.
Quick quiz
-
1. Who should decide that Ananya’s balance is ₹1,200?
- A) The model, if the system prompt describes the register
- B) Your JavaScript function, which reads the official register
- C) A default number in the tool description
Show answer
B. The model may ask for a lookup. Only your code should return the official rupee amount.
-
2. Where are the function arguments usually found in the first API response?
- A)
choices[0].message.tool_calls[0].function.arguments(a JSON string) - B)
choices[0].message.content - C) The
Authorizationheader
Show answer
A. Parse that string with
JSON.parse, then check the fields. The first message’scontentis often empty when a tool is requested. - A)
-
3. After
getFeeBalancereturns{"amount_inr":1200}, how do you send it back?- A) A message with
role: "tool"and the sametool_call_id - B) A new system prompt that includes the API key
- C) A
fetchfrom a<script>tag in the browser, with the key in the page
Show answer
A. Append the assistant’s
tool_callsmessage and atoolmessage, then call the API again. The key stays on the server. - A) A message with
-
4. Where should
AI_API_KEYlive?- A) In front-end JavaScript so the page can call the provider directly
- B) In the Node.js process environment, read from
process.env - C) Inside the tool arguments the model generates
Show answer
B. Front-end script is public. Tool arguments are also not a place for secrets. Use an environment variable on the server.
Related lessons
- Call a Chat API from JavaScript: Node.js and the Browser — the basic
fetchcall this lesson builds on, and why the key must stay off the front end. - How to Parse JSON from an AI API in PHP — the same idea of checking structured output in code, from PHP.
- Prompt Engineering for Developers: Clear Instructions, Examples and JSON Output — how to write the system instructions that tell the model when to use a tool.