Custom AI Functions
Allow WAzion’s AI to call your external APIs during conversations to retrieve information or perform actions in real time.
1. Introduction
Custom Functions allow WAzion’s AI to call your external APIs during a conversation with a customer. This enables querying information in real time or performing actions automatically.
How does it work?
- 1 The customer asks something (e.g., “Do you have product X available?“)
- 2 The AI detects that it needs external information
- 3 WAzion calls your API with the necessary parameters
- 4 Your API responds with the requested information
- 5 The AI uses that information to respond to the customer
Typical use cases
- • Check availability of products/services
- • Make automatic reservations
- • Check order status
- • Consult dynamic pricing
- • Search for customer information
- • Check available schedules
2. JSON Structure
Functions are defined as a JSON array. Each function has a name, description, and parameters that include the endpoint to call.
[
{
"name": "nombreDeLaFuncion",
"description": "Descripción clara de qué hace esta función",
"parameters": {
"type": "object",
"properties": {
"parametro1": {
"type": "string",
"description": "Descripción del parámetro"
},
"parametro2": {
"type": "number",
"description": "Otro parámetro"
},
"endpoint": {
"url": "https://tu-api.com/endpoint",
"method": "GET",
"format": "json",
"auth": {
"type": "header",
"fields": {
"Authorization": "Bearer tu-token-aqui"
}
}
}
},
"required": ["parametro1"]
}
}
]
Main fields
name: Unique function identifierdescription: Describe when to use this functionparameters: Define the parameters and the endpoint
Endpoint object
url: Full URL of the endpoint (HTTPS)method: GET, POST, PUT, DELETE, PATCHformat: json the formauth: Authentication Settings
Important: The description of each function and parameter is crucial. The AI uses these descriptions to decide when to call each function.
3. Types of Authentication
WAzion supports 4 types of authentication to protect your endpoints:
Header Auth (Recommended)
SaferSend credentials as HTTP headers. Ideal for Bearer tokens or API Keys.
"auth": {
"type": "header",
"fields": {
"Authorization": "Bearer tu-token-secreto",
"X-API-Key": "otra-clave-si-necesitas"
}
}
Basic Auth
HTTP Basic Authentication with username and password (encoded in Base64).
"auth": {
"type": "basic",
"fields": {
"username": "tu-usuario",
"password": "tu-contraseña"
}
}
Query Auth
Send credentials as parameters in the URL. Less secure but simple.
"auth": {
"type": "query",
"fields": {
"api_key": "tu-api-key",
"secret": "tu-secret"
}
}
// Resultado: ?api_key=tu-api-key&secret=tu-secret
Body Auth
Include credentials in the request body (POST/PUT/PATCH only).
"auth": {
"type": "body",
"fields": {
"api_key": "tu-api-key",
"token": "tu-token"
}
}
// Se añade al JSON del body junto con los parámetros
Without authentication
If your endpoint does not require authentication, simply omit the “auth“ field from the endpoint object.
4. Technical Specifications
Timeouts
| Total timeout | 60s |
| Connect timeout | 10s |
Retries
| Maximum number of attempts | 4 |
| Strategy | Exponential backoff |
Retry schedule
| Attempt 1 | Immediate |
| Attempt 2 | 2s |
| Attempt 3 | 4s |
| Attempt 4 | 8s |
HTTP headers sent
| Header | Value |
|---|---|
| Content-Type | application/json |
| Accept | application/json |
| User-Agent | WAzion-Functions/1.0 |
| + Authentication headers | According to configuration |
HTTP codes that trigger retry
Codes without retry
Endpoint Requirements
- Mandatory HTTPS (valid SSL certificate)
- { “Respuesta“: “Valid JSON format“ }
- Content-Type: application/json in the response
- Response in less than 60 seconds
Reserved parameter: phone
If your function declares a parameter called “phone,“ WAzion will automatically overwrite it with the current client’s phone number in E.164 format (e.g., +34612345678). This ensures that the correct phone number of the client being conversed with is always used, regardless of the value sent by the AI. Use it to send notifications, log inquiries, or personalize responses according to the client.
5. Practical Examples
Example 1: Check availability
Allows the AI to check if a product is in stock.
[
{
"name": "consultarDisponibilidad",
"description": "Consulta si un producto específico está disponible en stock",
"parameters": {
"type": "object",
"properties": {
"producto": {
"type": "string",
"description": "Nombre o referencia del producto a consultar"
},
"cantidad": {
"type": "number",
"description": "Cantidad deseada (opcional, por defecto 1)"
},
"endpoint": {
"url": "https://tu-tienda.com/api/stock",
"method": "GET",
"format": "json",
"auth": {
"type": "header",
"fields": {
"Authorization": "Bearer token-secreto-123"
}
}
}
},
"required": ["producto"]
}
}
]
Example 2: Create a reservation
Allows the AI to automatically create reservations in your system.
[
{
"name": "crearReserva",
"description": "Crea una reserva para el cliente en la fecha y hora indicada",
"parameters": {
"type": "object",
"properties": {
"nombre_cliente": {
"type": "string",
"description": "Nombre completo del cliente"
},
"fecha": {
"type": "string",
"description": "Fecha de la reserva en formato YYYY-MM-DD"
},
"hora": {
"type": "string",
"description": "Hora de la reserva en formato HH:MM"
},
"servicio": {
"type": "string",
"description": "Tipo de servicio a reservar"
},
"endpoint": {
"url": "https://tu-negocio.com/api/reservas",
"method": "POST",
"format": "json",
"auth": {
"type": "header",
"fields": {
"X-API-Key": "mi-api-key-secreta"
}
}
}
},
"required": ["nombre_cliente", "fecha", "hora", "servicio"]
}
}
]
Example 3: Check order status
Allows the AI to check the status of an order using its reference number.
[
{
"name": "consultarPedido",
"description": "Consulta el estado de envío de un pedido por su número",
"parameters": {
"type": "object",
"properties": {
"numero_pedido": {
"type": "string",
"description": "Número de pedido o referencia"
},
"endpoint": {
"url": "https://tu-tienda.com/api/pedidos/estado",
"method": "GET",
"format": "json",
"auth": {
"type": "query",
"fields": {
"token": "mi-token-secreto"
}
}
}
},
"required": ["numero_pedido"]
}
}
]
6. Sample Code
Examples of how to implement the endpoints on your server:
<?php
// Endpoint: /api/stock
header('Content-Type: application/json');
// Verificar autenticación
$authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
if ($authHeader !== 'Bearer token-secreto-123') {
http_response_code(401);
echo json_encode(['error' => 'Unauthorized']);
exit;
}
// Get parameters
$producto = $_GET['producto'] ?? '';
$cantidad = intval($_GET['cantidad'] ?? 1);
// Query your database
$stock = consultarStockEnBD($producto);
// Respond
echo json_encode([
'producto' => $producto,
'disponible' => $stock >= $cantidad,
'stock_actual' => $stock,
'mensaje' => $stock >= $cantidad
? "Yes, we have $stock units available"
: "Sorry, only $stock units left"
]);
// Endpoint: /api/stock
app.get('/api/stock', (req, res) => {
// Verificar autenticación
const authHeader = req.headers.authorization;
if (authHeader !== 'Bearer token-secreto-123') {
return res.status(401).json({ error: 'Unauthorized' });
}
// Get parameters
const { producto, cantidad = 1 } = req.query;
// Query your database
const stock = consultarStockEnBD(producto);
// Respond
res.json({
producto,
disponible: stock >= cantidad,
stock_actual: stock,
mensaje: stock >= cantidad
? `Yes, we have ${stock} units available`
: `Sorry, only ${stock} units left`
});
});
# Endpoint: /api/stock
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/api/stock', methods=['GET'])
def consultar_stock():
# Verificar autenticación
auth_header = request.headers.get('Authorization', '')
if auth_header != 'Bearer token-secreto-123':
return jsonify({'error': 'Unauthorized'}), 401
# Get parameters
producto = request.args.get('producto', '')
cantidad = int(request.args.get('cantidad', 1))
# Query your database
stock = consultar_stock_en_bd(producto)
# Respond
return jsonify({
'producto': producto,
'disponible': stock >= cantidad,
'stock_actual': stock,
'mensaje': f'Yes, we have {stock} units available'
if stock >= cantidad
else f'Sorry, only {stock} units left'
})
Change log
No recent changes in this documentation.