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
Special parameter: _phone
WAzion automatically adds the parameter “_phone“ with the customer’s phone number in E.164 format (e.g., +34612345678). You can use it to personalize the response or record who made the inquiry.
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' => 'No autorizado']);
exit;
}
// Obtener parámetros
$producto = $_GET['producto'] ?? '';
$cantidad = intval($_GET['cantidad'] ?? 1);
// Consultar tu base de datos
$stock = consultarStockEnBD($producto);
// Responder
echo json_encode([
'producto' => $producto,
'disponible' => $stock >= $cantidad,
'stock_actual' => $stock,
'mensaje' => $stock >= $cantidad
? "Sí, tenemos $stock unidades disponibles"
: "Lo sentimos, solo quedan $stock unidades"
]);
// 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: 'No autorizado' });
}
// Obtener parámetros
const { producto, cantidad = 1 } = req.query;
// Consultar tu base de datos
const stock = consultarStockEnBD(producto);
// Responder
res.json({
producto,
disponible: stock >= cantidad,
stock_actual: stock,
mensaje: stock >= cantidad
? `Sí, tenemos ${stock} unidades disponibles`
: `Lo sentimos, solo quedan ${stock} unidades`
});
});
# 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': 'No autorizado'}), 401
# Obtener parámetros
producto = request.args.get('producto', '')
cantidad = int(request.args.get('cantidad', 1))
# Consultar tu base de datos
stock = consultar_stock_en_bd(producto)
# Responder
return jsonify({
'producto': producto,
'disponible': stock >= cantidad,
'stock_actual': stock,
'mensaje': f'Sí, tenemos {stock} unidades disponibles'
if stock >= cantidad
else f'Lo sentimos, solo quedan {stock} unidades'
})
Change log
No recent changes in this documentation.