Tool Calling in a Telegram Bot on Node.js: Auto-calling get_order and create_booking via LLM

Classic Telegram bot scenarios with a rigid inline button hierarchy or regular expressions break as soon as a user writes a free-form request. Integrating Large Language Models (LLMs) with Function Calling (Tool Calling) support makes it possible to turn a bot into an autonomous agent. The model itself decides whether to request статус заказа, book a service, or simply answer a question based on a knowledge base.

In this guide, we will break down building an agent loop in Node.js without third-party heavy frameworks. The bot will accept an incoming webhook from Telegram, send the context to the LLM, execute local business functions (get_order, create_booking), and return the final response to the user. The main architectural rule is that the model never gets direct access to services, databases, or the secret TELEGRAM_BOT_TOKEN token. All calls are strictly controlled by your backend.

1. Defining Tool Schemas in JSON Schema

To help the LLM understand which functions are available and what arguments are required for execution, we pass a tools array. Each function is described according to the JSON Schema specification. The model analyzes the user's message ("Where is my order #8492?" or "Book me for tomorrow at 15:00") and returns structures with a call to a specific tool.

Let's create a tools.js file where we will define two tools: getting order status and creating a booking.

// tools.js

export const tools = [
{
type: 'function',
function: {
name: 'get_order',
description: 'Получить информацию о текущем статусе заказа по его ID',
parameters: {
type: 'object',
properties: {
order_id: {
type: 'string',
description: 'Уникальный номер заказа, например 10452'
}
},
required: ['order_id'],
additionalProperties: false
}
}
},
{
type: 'function',
function: {
name: 'create_booking',
description: 'Создать запись на услугу на определенную дату и время',
parameters: {
type: 'object',
properties: {
service_name: {
type: 'string',
description: 'Название услуги (например: Консультация, Стрижка)'
},
booking_date: {
type: 'string',
description: 'Дата записи в формате YYYY-MM-DD'
},
booking_time: {
type: 'string',
description: 'Время записи в формате HH:mm'
}
},
required: ['service_name', 'booking_date', 'booking_time'],
additionalProperties: false
}
}
}
];

2. Execution Layer: Handling Tool Functions

When the LLM decides to call a tool, it returns a tool_calls object containing the function name and a JSON string with arguments. The Node.js server's task is to validate these arguments, execute a request to the internal CRM or database, and return the result back to the model in JSON format.

Let's create a services.js file implementing validation and execution of business logic:

// services.js

// Имитация БД или API CRM-системы
async function dbGetOrder(orderId) {
const mockOrders = {
'10452': { status: 'доставляется', total: 3500, eta: 'сегодня до 18:00' },
'99811': { status: 'выполнен', total: 1200, eta: 'вчера' }
};
return mockOrders[orderId] || null;
}

async function dbCreateBooking(service, date, time, userId) {
// В реальном проекте здесь идет INSERT в PostgreSQL/MySQL
const bookingId = Math.floor(100000 + Math.random() * 900000);
return {
success: true,
booking_id: bookingId,
service,
date,
time,
user_id: userId
};
}

export async function executeTool(toolCall, telegramUserId) {
const name = toolCall.function.name;
let args = {};

try {
args = JSON.parse(toolCall.function.arguments);
} catch (err) {
return JSON.stringify({ error: 'Invalid JSON in tool call arguments' });
}

if (name === 'get_order') {
const order = await dbGetOrder(args.order_id);
if (!order) {
return JSON.stringify({ status: 'not_found', message: `Заказ #${args.order_id} не найден.` });
}
return JSON.stringify({ status: 'success', data: order });
}

if (name === 'create_booking') {
const booking = await dbCreateBooking(
args.service_name,
args.booking_date,
args.booking_time,
telegramUserId
);
return JSON.stringify({ status: 'success', data: booking });
}

return JSON.stringify({ error: `Unknown tool: ${name}` });
}

3. Agent Loop (LLM Loop) and Telegram Webhook Handler

The agent LLM workflow loop consists of several steps:

  1. Receiving an incoming message from Telegram via Webhook.
  2. Building the message array (system prompt + history + current request).
  3. Sending the request to the LLM, passing the tools array.
  4. Checking the response: if the model returned tool_calls, we execute each function via executeTool(), add the results to history with the tool role, and make a subsequent request to the LLM.
  5. When the model generates the final text response, we send it to the user via the Telegram Bot API sendMessage method.

To handle HTTP requests to the Telegram API, we use Node.js built-in fetch (version 18+). Secret keys are obtained from process.env environment variables.

// server.js
import http from 'node:http';
import { tools } from './tools.js';
import { executeTool } from './services.js';

const TELEGRAM_BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN;
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const SECRET_WEBHOOK_TOKEN = process.env.SECRET_WEBHOOK_TOKEN;

if (!TELEGRAM_BOT_TOKEN || !OPENAI_API_KEY) {
throw new Error('Missing environment variables: TELEGRAM_BOT_TOKEN or OPENAI_API_KEY');
}

// Отправка сообщения пользователю в Telegram
async function sendTelegramMessage(chatId, text) {
const url = `https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage`;
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chat_id: chatId,
text: text,
parse_mode: 'HTML'
})
});

const data = await response.json();
if (!response.ok || !data.ok) {
console.error('Telegram API error:', data);
throw new Error(`Telegram error ${data.error_code}: ${data.description}`);
}
return data;
}

// Взаимодействие с OpenAI Chat Completions API
async function callOpenAI(messages) {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${OPENAI_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'gpt-4o-mini',
messages: messages,
tools: tools,
tool_choice: 'auto'
})
});

if (!response.ok) {
const errText = await response.text();
throw new Error(`OpenAI API error ${response.status}: ${errText}`);
}

const data = await response.json();
return data.choices[0].message;
}

// Главный агентский цикл
async function processUserMessage(chatId, userId, userText) {
const messages = [
{
role: 'system',
content: 'Ты — вежливый ассистент поддержки сервиса. Отвечай кратко и точно. Для запросов о заказах или бронировании обязательно используй доступные инструменты.'
},
{ role: 'user', content: userText }
];

let assistantMessage = await callOpenAI(messages);
messages.push(assistantMessage);

// Цикл обработки tool_calls (модель может вызвать 1 или несколько функций подряд)
while (assistantMessage.tool_calls && assistantMessage.tool_calls.length > 0) {
for (const toolCall of assistantMessage.tool_calls) {
console.log(`[LLM Tool Call] ${toolCall.function.name}`);
const toolResult = await executeTool(toolCall, userId);

messages.push({
role: 'tool',
tool_call_id: toolCall.id,
content: toolResult
});
}

// Повторный вызов модели с передачей результатов функций
assistantMessage = await callOpenAI(messages);
messages.push(assistantMessage);
}

// Финальный ответ модели пользователю
if (assistantMessage.content) {
await sendTelegramMessage(chatId, assistantMessage.content);
}
}

// HTTP Server для приёма Webhook от Telegram
const server = http.createServer(async (req, res) => {
if (req.method === 'POST' && req.url === '/webhook') {
// Проверка заголовка X-Telegram-Bot-Api-Secret-Token
if (SECRET_WEBHOOK_TOKEN && req.headers['x-telegram-bot-api-secret-token'] !== SECRET_WEBHOOK_TOKEN) {
res.writeHead(403);
return res.end('Forbidden');
}

let body = '';
req.on('data', chunk => { body += chunk; });
req.on('end', async () => {
try {
const update = JSON.parse(body);

// Быстрый ответ 200 OK для Telegram, чтобы избежать таймаутов
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ ok: true }));

if (update.message && update.message.text) {
const chatId = update.message.chat.id;
const userId = update.message.from.id;
const text = update.message.text;

// Исполняем цикл асинхронно
await processUserMessage(chatId, userId, text);
}
} catch (err) {
console.error('Webhook handler error:', err);
}
});
} else {
res.writeHead(404);
res.end();
}
});

server.listen(3000, () => {
console.log('Server running on port 3000');
});

4. Important Security Rules and Limitations

  • Never pass tokens to the LLM. The model receives only anonymized data (order IDs, time slots, error texts). Requests to the Telegram Bot API and database happen strictly on the Node.js server.
  • Validate LLM arguments. The model may generate an invalid date or malformed JSON. Wrap JSON.parse() in a try/catch block and check data formats before executing SQL queries.
  • Respect Telegram timeouts. Telegram waits for a Webhook response for no more than 5 seconds. Always send HTTP 200 OK immediately upon receiving updates, and run the LLM agent loop in the background (or via task queues like Redis/BullMQ).
  • Protect the Webhook. Always check the X-Telegram-Bot-Api-Secret-Token header when registering the webhook via the secret_token parameter. This guarantees that requests originate strictly from Telegram servers.

If you need to quickly launch a reliable smart bot or scale a Telegram integration for business, the experts at BotCreator will help design the architecture and connect the necessary LLM models.

New articles on Telegram

We explain what to automate in your business and how it works in practice. No spam.