Volver al panel

Documentación

Aprende a usar Asyntai

Referencia API

Cree integraciones personalizadas con la API REST de Asyntai

Obtener clave API

Plan de pago requerido: El acceso a la API está disponible en los planes Starter, Standard y Pro. Ver precios

Descripción general

The Asyntai API allows you to integrate AI-powered customer support into any application. Send messages and receive intelligent responses grounded in your website content and knowledge base.

Autenticación

All API requests require authentication using your API key. You can get your API key from the API Settings page.

Incluya su clave API en las solicitudes usando uno de estos métodos:

  • Encabezado Authorization (recomendado): Authorization: Bearer TU_CLAVE_API
  • Encabezado X-API-Key: X-API-Key: TU_CLAVE_API

Mantenga su clave API en secreto. Cualquiera con su clave puede acceder a su cuenta a través de la API. Nunca la expongas en código del lado del cliente.

URL base

https://asyntai.com/api/v1/

Endpoints

POST /chat/

Envíe un mensaje y recibe una respuesta generada por IA.

Cuerpo de la solicitud

{
  "message": "What are your business hours?",
  "session_id": "user_123",      // optional
  "website_id": 1                 // optional
}
Parámetro Tipo Requerido Descripción
message string Sí El mensaje del usuario para enviar a la IA
session_id string No Identificador único de la conversación. Use el mismo session_id para mantener el historial de la conversación.
website_id integer No ID de sitio web específico. Si no se proporciona, usa tu sitio web principal.

Respuesta

{
  "success": true,
  "response": "Our business hours are Monday-Friday, 9 AM to 5 PM EST.",
  "session_id": "user_123"
}

Ejemplo (cURL)

curl -X POST https://asyntai.com/api/v1/chat/ \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"message": "What are your business hours?", "session_id": "user_123"}'

Ejemplo (Python)

import requests

response = requests.post(
    "https://asyntai.com/api/v1/chat/",
    headers={
        "Authorization": "Bearer YOUR_API_KEY",
        "Content-Type": "application/json"
    },
    json={
        "message": "What are your business hours?",
        "session_id": "user_123"
    }
)

data = response.json()
print(data["response"])

Ejemplo (JavaScript)

const response = await fetch("https://asyntai.com/api/v1/chat/", {
  method: "POST",
  headers: {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    message: "What are your business hours?",
    session_id: "user_123"
  })
});

const data = await response.json();
console.log(data.response);

GET /websites/

Lista todos los sitios web asociados a su cuenta.

Respuesta

{
  "success": true,
  "websites": [
    {
      "id": 1,
      "name": "My Website",
      "domain": "example.com",
      "is_primary": true
    }
  ]
}

Ejemplo (cURL)

curl https://asyntai.com/api/v1/websites/ \
  -H "Authorization: Bearer YOUR_API_KEY"

POST /websites/

Create a new AI agent. This does the same thing as adding a website in your dashboard: it makes the agent, reads your site, and writes the first draft of the AI instructions.

Use this to set up customers from your own software. You get back the widget ID and the code to put on the website.

Cuerpo de la solicitud

Campo Tipo Descripción
domain string Required. The website address, for example example.com
name string Optional. A display name for the agent. Useful when one website has several agents.
crawl boolean Optional, true by default. Set it to false to create the agent without reading the website. Nothing is crawled and no instructions are written.
force boolean Optional, false by default. Set it to true to add a website you already have. The copy is stored with a number after it.

Respuesta

{
  "success": true,
  "website": {
    "id": 42,
    "domain": "example.com",
    "name": "Support agent",
    "widget_id": "asyntai_ab12cd34ef56",
    "is_primary": true,
    "crawl_started": true,
    "instructions_status": "generating",
    "job_id": "8f2c1e90-..."
  },
  "embed_code": "<script>...</script>"
}

Ejemplo (cURL)

curl -X POST https://asyntai.com/api/v1/websites/ \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"domain": "example.com", "name": "Support agent"}'

Reading a website takes a few minutes, so this call answers straight away. Check when the agent is ready with the next endpoint.

Errors

Code Meaning
403 You have reached the number of websites your plan allows. The answer tells you the limit.
409 Your account already has this website. Send force as true to add it again.

GET /websites/{id}/

Get one website and see whether it is ready. Use this after you create an agent, to wait until the website has been read and the AI instructions are written.

Respuesta

{
  "success": true,
  "website": {
    "id": 42,
    "domain": "example.com",
    "name": "Support agent",
    "widget_id": "asyntai_ab12cd34ef56",
    "is_primary": true,
    "created_at": "2026-08-11T09:12:00+00:00",
    "ready": true,
    "instructions": {
      "status": "completed",
      "has_instructions": true,
      "characters": 3421
    },
    "crawl": {
      "job_id": "8f2c1e90-...",
      "status": "completed",
      "pages_crawled": 47,
      "pages_found": 50,
      "max_pages": 50,
      "completed_at": "2026-08-11T09:15:31+00:00",
      "error": ""
    },
    "knowledge_items": 47
  },
  "embed_code": "<script>...</script>"
}

The ready field is true when nothing is still running. A crawl that failed also counts as ready, because it has finished. Look at the crawl status to see what happened.

Ejemplo (cURL)

curl https://asyntai.com/api/v1/websites/42/ \
  -H "Authorization: Bearer YOUR_API_KEY"

GET PATCH /websites/{id}/settings/

Read or change the chat widget settings for one website. These are the same settings you see on the Customize page: colours, the name of the assistant, the first message, lead capture, and everything else.

Reading the settings

A GET request returns every setting with its current value, plus a locked list. Locked shows the settings your plan cannot change, and which plans they need.

{
  "success": true,
  "settings": {
    "ai_support_name": "AI Assistant",
    "widget_color": "#0B0D10",
    "initial_message": "Hi, how can I help you?",
    "hide_branding": false,
    "...": "..."
  },
  "locked": {
    "hide_branding": ["pro", "enterprise"],
    "widget_style": ["pro", "enterprise"]
  }
}

Changing the settings

A PATCH request changes only the settings you send. Everything you leave out stays as it is.

curl -X PATCH https://asyntai.com/api/v1/websites/42/settings/ \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"ai_support_name": "Ava", "widget_color": "#0f172a", "use_emoji": true}'
{
  "success": true,
  "updated": ["ai_support_name", "use_emoji", "widget_color"],
  "settings": { "...": "..." },
  "locked": { "...": "..." }
}

Plans

Each setting needs its own plan, the same as in the dashboard. For example, hiding the Asyntai branding needs the Pro plan, and voice input needs Standard.

Plan needed Ajustes Examples
Any paid plan 25 widget_color, ai_support_name, initial_message
Desde el plan Starter 22 profile_picture, conversation_starters_enabled
Desde el plan Standard 25 speech_to_text_enabled, image_vision_enabled, escalation_enabled
Pro 6 hide_branding, widget_style

If you send a setting your plan does not allow, the whole request is refused with code 403 and nothing is saved. The same happens if any value is wrong, for example a colour that is not a hex code. Your settings never end up half changed.

GET PUT /websites/{id}/instructions/

Read or replace the AI instructions for one website. These are the rules that tell the assistant who it is, what it may say, and what it must not say. They are the same instructions you edit in the dashboard.

Reading

{
  "success": true,
  "instructions": "You are the support agent for Acme Tools...",
  "characters": 1979,
  "version": 7,
  "mode": "instructions",
  "ask_questions": true,
  "generation_status": "completed",
  "being_edited_by": null
}

Replacing

A PUT request replaces the whole text, the same as saving in the dashboard. There is no append mode. To add a paragraph, read the instructions, add your text, then write it back.

curl -X PUT https://asyntai.com/api/v1/websites/42/instructions/ \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"instructions": "You are the support agent for Acme Tools...", "version": 7}'

Cuerpo de la solicitud

Campo Tipo Descripción
instructions string Required. The complete new text. It replaces everything that was there.
version number Optional but recommended. The version you read. If somebody changed the instructions since then, your write is refused instead of overwriting their work.
mode string Optional. Either instructions or general.
ask_questions boolean Optional. Whether the assistant asks a follow-up question at the end of its answers.
force boolean Optional, false by default. Needed only when your new text is less than half the length of the current text.

How your instructions are protected

Instructions can take hours to write, so a write can be refused to protect them:

Code Meaning
400 Your new text is less than half the length of the current text. This catches a script that sends empty or cut-off text over instructions somebody spent hours on. Send force as true if you meant it.
409 The instructions changed after you read them. Read them again, apply your change, then write.
423 Somebody is editing the instructions in the dashboard right now. The answer tells you who. Try again in a couple of minutes.

Every change also saves a copy of the previous text, so an earlier version can always be restored from the dashboard.

GET /conversations/

Recupera el historial de conversación para una sesión específica.

Parámetros de consulta

Parámetro Tipo Requerido Descripción
session_id string Sí El ID de sesión para recuperar el historial
limit integer No Máximo de mensajes a devolver (predeterminado: 50, máx.: 100)

Respuesta

{
  "success": true,
  "session_id": "user_123",
  "messages": [
    {
      "role": "user",
      "content": "What are your business hours?",
      "timestamp": "2024-01-15T10:30:00Z"
    },
    {
      "role": "assistant",
      "content": "Our business hours are Monday-Friday, 9 AM to 5 PM EST.",
      "timestamp": "2024-01-15T10:30:01Z",
      "sender_type": "ai",
      "agent_name": null,
      "response_time_ms": 1840.5
    }
  ]
}

Una pregunta y su respuesta se guardan en un mismo registro, por lo que ambas llevan el mismo timestamp. No reste uno del otro para medir la velocidad de respuesta, porque el resultado siempre es cero. Use response_time_ms, que es el tiempo real que tardó la respuesta, en milisegundos.

sender_type es ai cuando respondió el chatbot y human cuando uno de sus agentes tomó el control del chat. agent_name contiene el nombre visible de ese agente.

Ejemplo (cURL)

curl "https://asyntai.com/api/v1/conversations/?session_id=user_123&limit=20" \
  -H "Authorization: Bearer YOUR_API_KEY"

GET /sessions/

Lista sus sesiones de chat recientes. Use esto para descubrir IDs de sesión, que luego puede pasar a /conversations/ para recuperar el historial completo de mensajes.

Parámetros de consulta

Parámetro Tipo Requerido Descripción
limit integer No Número de sesiones recientes a devolver (por defecto: 20, máx: 100)
website_id string No Filtrar sesiones por un ID de sitio web específico
source string No Filtrar por fuente de sesión: widget, api, whatsapp, instagram, messenger, gorgias, freshchat, zapier
since string No Solo sesiones cuyo último mensaje sea en esta fecha ISO o después, por ejemplo 2024-01-15
before string No Solo sesiones cuyo último mensaje sea anterior a esta fecha u hora ISO. Úsalo para paginar hacia atrás, ver más abajo.

Respuesta

{
  "success": true,
  "sessions": [
    {
      "session_id": "session_abc123def",
      "source": "widget",
      "message_count": 5,
      "first_message": "What are your business hours?",
      "first_message_at": "2024-01-15T10:30:00Z",
      "last_message_at": "2024-01-15T10:35:00Z",
      "first_response_time_ms": 1840.5,
      "first_human_response_at": null,
      "started_at": "2024-01-15T10:29:58Z",
      "ended_at": "2024-01-15T10:41:12Z",
      "taken_over_at": null,
      "page_url": "https://example.com/pricing",
      "country": "Germany",
      "category": "Pricing",
      "website_domain": "example.com"
    }
  ]
}

Campos de marca de tiempo para informes

Campo Descripción
started_at Cuándo abrió el visitante el chat. Solo está disponible para sesiones del widget, porque las sesiones creadas a través de la API nunca abren un widget.
first_message_at Cuándo se guardó el primer mensaje de la conversación.
first_response_time_ms Cuánto tardó la primera respuesta, en milisegundos. Use esto para el tiempo de primera respuesta.
first_human_response_at Cuándo envió uno de sus agentes la primera respuesta. El valor es null cuando el chatbot gestionó toda la conversación.
taken_over_at Cuándo tomó un agente el control del chat de manos del chatbot.
last_message_at Cuándo se guardó el último mensaje de la conversación.
ended_at Cuándo salió el visitante del chat. Un chat no tiene estado resuelto ni cerrado, porque un visitante siempre puede volver y hacer otra pregunta.

Todas las marcas de tiempo están en UTC y usan el formato ISO 8601. No se puede cambiar la zona horaria. Convierta los valores en su propia herramienta de informes.

Otros campos para informes

Campo Descripción
page_url La página en la que estaba el visitante cuando empezó el chat. Disponible solo para sesiones del widget.
country El país del visitante, según la dirección IP en el momento del chat. Disponible solo para sesiones del widget.
category El tema de las categorías de chat. Vacío cuando la función está desactivada o el proceso diario aún no ha etiquetado este chat.

Ejemplo (cURL)

curl "https://asyntai.com/api/v1/sessions/?since=2024-01-01&limit=100" \
  -H "Authorization: Bearer YOUR_API_KEY"

Paginar por el historial

Una llamada devuelve como máximo 100 sesiones, las más recientes primero. Para leer más atrás, toma el last_message_at de la última sesión de la página y pásalo como before en la siguiente llamada. Repite hasta que una llamada devuelva una lista vacía.

import requests

url = "https://asyntai.com/api/v1/sessions/"
headers = {"Authorization": "Bearer YOUR_API_KEY"}
params = {"since": "2024-01-01", "limit": 100}

sessions = []
while True:
    page = requests.get(url, headers=headers, params=params).json()["sessions"]
    if not page:
        break
    sessions.extend(page)
    params["before"] = page[-1]["last_message_at"]

print(len(sessions), "sessions since 2024-01-01")

GET /leads/

Recuperar leads recopilados — direcciones de correo electrónico y números de teléfono enviados por visitantes durante conversaciones de chat.

Parámetros de consulta

Parámetro Tipo Requerido Descripción
limit integer No Número de leads a devolver (predeterminado: 50, máx: 100)
website_id string No Filtrar leads por un ID de sitio web específico
since string No Solo leads iniciados en esta fecha ISO o después, por ejemplo 2024-01-15
before string No Solo leads iniciados antes de esta fecha u hora ISO. Úsalo para retroceder por todo el historial.

Respuesta

{
  "success": true,
  "leads": [
    {
      "session_id": "session_abc123def",
      "email": "[email protected]",
      "phone": "+1234567890",
      "page_url": "https://example.com/pricing",
      "started_at": "2024-01-15T10:30:00Z"
    }
  ]
}
Campo Tipo Descripción
session_id string El ID de sesión del chat. Páselo a /conversations/ para ver el historial completo del chat.
email cadena o null Dirección de correo electrónico proporcionada por el visitante, o null si no se recopiló
phone cadena o null Número de teléfono proporcionado por el visitante, o null si no se recopiló
page_url cadena o null La URL de la página donde el visitante estaba chateando
started_at string Marca de tiempo ISO 8601 de cuándo comenzó la sesión de chat

Ejemplo (cURL)

curl "https://asyntai.com/api/v1/leads/?limit=20" \
  -H "Authorization: Bearer YOUR_API_KEY"

Ejemplo (Python)

import requests

response = requests.get(
    "https://asyntai.com/api/v1/leads/",
    headers={"Authorization": "Bearer YOUR_API_KEY"},
    params={"limit": 20}
)

leads = response.json()["leads"]
for lead in leads:
    print(f"{lead['email'] or ''} | {lead['phone'] or ''}")

GET /tickets/

Obtén los tickets de soporte con las marcas de tiempo que necesitas para medir los tiempos de gestión: cuándo llegó el ticket, cuándo lo tomó alguien, cuándo se respondió por primera vez y cuándo se resolvió.

Parámetros de consulta

Parámetro Tipo Requerido Descripción
limit integer No Número de tickets a devolver (por defecto: 50, máximo: 100)
website_id string No Filtrar tickets por ID del sitio web o por el dominio del sitio web, por ejemplo example.com
name string No Filtrar por cualquier parte del nombre del visitante, por ejemplo anna
status string No Filtrar por estado: open, in_progress, resolved o closed
since string No Solo los tickets creados en esta fecha ISO o después, por ejemplo 2024-01-15
before string No Solo tickets creados antes de esta fecha u hora ISO. Úsalo para paginar hacia atrás, ver más abajo.

Respuesta

{
  "success": true,
  "tickets": [
    {
      "ticket_number": "TKT-00001",
      "session_id": "session_abc123def",
      "status": "resolved",
      "priority": "medium",
      "subject": "Cannot complete checkout",
      "visitor_email": "[email protected]",
      "visitor_name": "Anna Novak",
      "page_url": "https://example.com/checkout",
      "website_id": 12,
      "channel": "session",
      "assigned_to": "[email protected]",
      "created_at": "2024-01-15T10:30:00Z",
      "first_assigned_at": "2024-01-15T10:41:00Z",
      "first_response_at": "2024-01-15T11:02:00Z",
      "resolved_at": "2024-01-15T12:20:00Z"
    }
  ]
}
Campo Tipo Descripción
ticket_number string La referencia del ticket que se muestra en tu panel
session_id string La sesión de chat de la que salió el ticket. Pásala a /conversations/ para leer toda la conversación que hay detrás del ticket.
visitor_name cadena o null El nombre del visitante, o null si el visitante no lo indicó
status string Uno de: open, in_progress, resolved, closed
priority string Uno de: low, medium, high
channel string De dónde llegó la conversación, por ejemplo session para el chat web
assigned_to cadena o null El miembro del equipo que tiene el ticket, o null si nadie lo ha tomado
created_at string Cuándo se creó el ticket
first_assigned_at cadena o null Cuándo tomó alguien el ticket por primera vez. Null si nadie lo ha hecho.
first_response_at cadena o null Cuándo se envió la primera respuesta desde Asyntai. Null si no ha habido respuesta desde Asyntai.
resolved_at cadena o null Cuándo se marcó el ticket como resuelto. Null mientras siga abierto.

Solo vemos las respuestas enviadas desde Asyntai. Si tu equipo responde a un visitante desde su propio buzón, nunca lo vemos, y first_response_at queda vacío aunque el visitante haya recibido respuesta. Tenlo en cuenta antes de promediar estos números.

Todas las marcas de tiempo están en UTC y usan el formato ISO 8601. Los tickets creados antes de esta función no tienen first_assigned_at ni first_response_at, porque esos tiempos nunca se registraron.

Ejemplo (cURL)

curl "https://asyntai.com/api/v1/tickets/?status=resolved&limit=20" \
  -H "Authorization: Bearer YOUR_API_KEY"

Ejemplo (Python)

import requests
from datetime import datetime

response = requests.get(
    "https://asyntai.com/api/v1/tickets/",
    headers={"Authorization": "Bearer YOUR_API_KEY"},
    params={"since": "2024-01-01", "limit": 100}
)

for ticket in response.json()["tickets"]:
    if ticket["first_response_at"]:
        created = datetime.fromisoformat(ticket["created_at"])
        replied = datetime.fromisoformat(ticket["first_response_at"])
        print(ticket["ticket_number"], replied - created)

Paginar por el historial

Una llamada devuelve como máximo 100 tickets, los más recientes primero. Para leer más atrás, toma el created_at del último ticket de la página y pásalo como before en la siguiente llamada. Repite hasta que una llamada devuelva una lista vacía.

import requests

url = "https://asyntai.com/api/v1/tickets/"
headers = {"Authorization": "Bearer YOUR_API_KEY"}
params = {"since": "2024-01-01", "limit": 100}

tickets = []
while True:
    page = requests.get(url, headers=headers, params=params).json()["tickets"]
    if not page:
        break
    tickets.extend(page)
    params["before"] = page[-1]["created_at"]

print(len(tickets), "tickets since 2024-01-01")

GET /account/

Obtén la información de su cuenta y estadísticas de uso.

Respuesta

{
  "success": true,
  "account": {
    "email": "[email protected]",
    "plan": "starter",
    "messages_used": 150,
    "messages_limit": 800
  }
}

Ejemplo (cURL)

curl https://asyntai.com/api/v1/account/ \
  -H "Authorization: Bearer YOUR_API_KEY"

¿Múltiples sitios web? Los endpoints de la base de conocimiento usan su sitio web principal por defecto. Si tiene múltiples sitios web, envíe website_id para seleccionar uno específico. Puedes encontrar tus IDs de sitio web usando GET /websites/.

Límites diarios de carga: Las cargas a la base de conocimiento (texto, URL, hoja de cálculo) están sujetas a un límite diario de caracteres según su plan. Esto se aplica al total de contenido cargado en todos los endpoints de la base de conocimiento por día.

Plan Caracteres/día
Starter300,000
Standard1,500,000
Pro6,000,000

GET /knowledge/

Lista las entradas de su base de conocimiento. Estos son los contenidos que su chatbot IA usa para responder preguntas.

Parámetros de consulta

Parámetro Tipo Requerido Descripción
limit integer No Número de entradas a devolver (predeterminado: 50, máx.: 100)
website_id string No Filtrar por ID de sitio web (por defecto es su sitio web principal)

Respuesta

{
  "success": true,
  "entries": [
    {
      "id": "abc-123-def",
      "type": "text",
      "title": "Business Hours",
      "description": "Manual text content (150 words)",
      "created_at": "2024-01-15T10:30:00Z"
    },
    {
      "id": "ghi-456-jkl",
      "type": "url",
      "title": "About Us - Example",
      "description": "Content from https://example.com/about",
      "created_at": "2024-01-14T09:00:00Z"
    }
  ]
}

Ejemplo (cURL)

curl "https://asyntai.com/api/v1/knowledge/?limit=10" \
  -H "Authorization: Bearer YOUR_API_KEY"

POST /knowledge/text/

Añada contenido de texto personalizado a su base de conocimiento. La IA usará esto para responder las preguntas de los visitantes.

Cuerpo de la solicitud

{
  "title": "Return Policy",
  "content": "We offer a 30-day return policy on all items. Items must be unused and in original packaging. Refunds are processed within 5-7 business days.",
  "website_id": "123"
}
Parámetro Tipo Requerido Descripción
title string Sí Un título para esta entrada de conocimiento
content string Sí El contenido de texto (mínimo 10 caracteres)
website_id string No Sitio web de destino (por defecto es su sitio web principal)

Respuesta

{
  "success": true,
  "id": "abc-123-def",
  "title": "Return Policy",
  "chunks_created": 1
}

Ejemplo (cURL)

curl -X POST "https://asyntai.com/api/v1/knowledge/text/" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"title": "Return Policy", "content": "We offer a 30-day return policy..."}'

POST /knowledge/url/

Añada una página web a su base de conocimiento. El contenido será obtenido y extraído automáticamente.

Cuerpo de la solicitud

{
  "url": "https://example.com/faq",
  "website_id": "123"
}
Parámetro Tipo Requerido Descripción
url string Sí La URL de la que obtener el contenido
website_id string No Sitio web de destino (por defecto es su sitio web principal)

Respuesta

{
  "success": true,
  "id": "abc-123-def",
  "title": "FAQ - Example",
  "url": "https://example.com/faq",
  "chunks_created": 5
}

Ejemplo (cURL)

curl -X POST "https://asyntai.com/api/v1/knowledge/url/" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com/faq"}'

POST /knowledge/spreadsheet/

Suba un archivo CSV o Excel (.xlsx) a su base de conocimiento. Cada fila se convierte en una entrada de conocimiento separada, ideal para catálogos de productos, listas de preguntas frecuentes, tablas de precios y directorios.

Solicitud

Envía como multipart/form-data (carga de archivo), no JSON.

Parámetro Tipo Requerido Descripción
file archivo Sí Un archivo .csv o .xlsx. La primera fila debe ser encabezados de columna. Máximo de filas por carga: Starter 500, Standard 2,000, Pro 10,000. Las filas excedentes se truncan.
website_id string No Sitio web de destino (por defecto es su sitio web principal)

Respuesta

{
  "success": true,
  "id": "abc-123-def",
  "title": "products.csv",
  "rows_processed": 15,
  "chunks_created": 15
}

Ejemplo (cURL)

curl -X POST "https://asyntai.com/api/v1/knowledge/spreadsheet/" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "[email protected]"

GET /knowledge/{id}/

Lee una entrada de la base de conocimiento, incluido el texto guardado para ella. El valor id procede de la respuesta de GET /knowledge/.

Se devuelve el contenido de las entradas que usted añadió: texto, archivos, hojas de cálculo, URLs individuales y vídeos. El rastreo de un sitio web aparece en la lista, pero sus páginas no se devuelven, porque la fuente es su propio sitio web público. En ese caso content es null y el campo reason explica el motivo.

Respuesta

{
  "success": true,
  "id": "abc-123-def",
  "type": "text",
  "title": "Business Hours",
  "description": "Manual text content (150 words)",
  "created_at": "2024-01-15T10:30:00Z",
  "chunks_count": 3,
  "content": "We are open Monday to Friday, 9am to 5pm...",
  "content_available": true,
  "char_count": 43
}

Ejemplo (cURL)

curl "https://asyntai.com/api/v1/knowledge/abc-123-def/" \
  -H "Authorization: Bearer YOUR_API_KEY"

DELETE /knowledge/{id}/

Elimina una entrada de la base de conocimiento. El id se puede encontrar en la respuesta de GET /knowledge/.

Respuesta

{
  "success": true,
  "message": "Knowledge base entry deleted"
}

Ejemplo (cURL)

curl -X DELETE "https://asyntai.com/api/v1/knowledge/abc-123-def/" \
  -H "Authorization: Bearer YOUR_API_KEY"

Consejo: También puede gestionar webhooks desde la Configuración API página sin escribir código.

GET /webhooks/

Lista sus webhooks registrados.

Respuesta

{
  "success": true,
  "webhooks": [
    {
      "id": "abc-123-def",
      "url": "https://example.com/webhook",
      "events": ["message.received", "escalation.requested"],
      "is_active": true,
      "created_at": "2024-01-15T10:30:00Z"
    }
  ]
}

Ejemplo (cURL)

curl "https://asyntai.com/api/v1/webhooks/" \
  -H "Authorization: Bearer YOUR_API_KEY"

POST /webhooks/

Registra un nuevo webhook para recibir notificaciones de eventos en tiempo real.

Eventos disponibles

Evento Descripción
message.received Un visitante envió un mensaje y recibió una respuesta
conversation.started Se inició una nueva sesión de chat
escalation.requested La IA activó una transferencia a un agente humano
takeover.started Un agente humano tomó el control de una sesión de chat

Cuerpo de la solicitud

{
  "url": "https://example.com/webhook",
  "events": ["message.received", "escalation.requested"],
  "website_id": "123"
}
Parámetro Tipo Requerido Descripción
url string Sí La URL HTTPS para recibir solicitudes POST del webhook
events matriz Sí Lista de eventos a los que suscribirse (ver tabla anterior)
website_id string No Sitio web de destino (por defecto es su sitio web principal)

Respuesta

{
  "success": true,
  "webhook": {
    "id": "abc-123-def",
    "url": "https://example.com/webhook",
    "events": ["message.received", "escalation.requested"],
    "secret": "whsec_abc123...",
    "created_at": "2024-01-15T10:30:00Z"
  }
}

Verificación de webhooks: Cada webhook incluye un secret (mostrado solo al crearlo). Cada POST a su URL incluye un encabezado X-Webhook-Signature — un HMAC-SHA256 del cuerpo de la solicitud firmado con su secreto.

Ejemplo (cURL)

curl -X POST "https://asyntai.com/api/v1/webhooks/" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com/webhook", "events": ["message.received"]}'

DELETE /webhooks/{id}/

Elimina un webhook. El id se puede encontrar en la respuesta de GET /webhooks/.

Respuesta

{
  "success": true,
  "message": "Webhook deleted"
}

Ejemplo (cURL)

curl -X DELETE "https://asyntai.com/api/v1/webhooks/abc-123-def/" \
  -H "Authorization: Bearer YOUR_API_KEY"

Respuestas de error

Todas las respuestas de error siguen este formato:

{
  "success": false,
  "error": "Error message describing what went wrong"
}
Código de estado Descripción
400 Solicitud incorrecta - Parámetros no válidos o campos obligatorios faltantes
401 No autorizado - Clave API inválida o faltante
429 Demasiadas solicitudes - Límite de mensajes alcanzado para su plan
503 Servicio no disponible - Servicio de IA temporalmente no disponible

Límites de frecuencia

El uso de la API está limitado por su plan de suscripción:

  • Free: 50 mensajes/mes
  • Starter ($39/mes): 800 mensajes/mes
  • Standard ($139/mes): 15,000 mensajes/mes
  • Pro ($449/mes): 50,000 mensajes/mes

¿Necesita ayuda?

If you have any questions or run into issues, contact us at [email protected].