La guía definitiva de API para desarrolladores
La superficie API servidor a servidor revisada para crear integraciones Chirps seguras. Se excluyen intencionalmente los flujos de facturación y OAuth del panel, callbacks públicos del widget, webhooks de proveedores, cron y rutas internas.
1. Autenticación y principios básicos
URL base: https://chirps.cc
Todos los puntos finales de API requieren una clave API de Chirps en el encabezado "Autorización". Puede generar una clave API desde el Administrador de API en la [sección Desarrollador de su panel] (https://chirps.cc/dashboard/developers).
Authorization: Bearer <YOUR_CHIRPS_API_KEY>Solicitud de ejemplo:
curl -X GET https://chirps.cc/api/billing/usage \
-H "Authorization: Bearer <YOUR_CHIRPS_API_KEY>" \
-H "Content-Type: application/json"Manejo de errores estándar
| Código de estado | Descripción |
|---|---|
200 OK | La solicitud fue exitosa. |
400 Bad Request | La carga útil JSON falló en la validación. Incluye una matriz de detalles. |
401 Unauthorized | Token faltante o caducado. |
402 Payment Required | El espacio de trabajo ha alcanzado los límites de facturación. |
403 Forbidden | El usuario no tiene los permisos RBAC requeridos. |
404 Not Found | El recurso solicitado no existe. |
500 Server Error | Error inesperado de plataforma. |
409 Conflict | The request conflicts with current state, such as a booking slot that is no longer available. |
413 Payload Too Large | The request exceeds the endpoint's documented size limit. |
429 Too Many Requests | The API-key request limit was reached; retry after the current window resets. |
503 Service Unavailable | A required safety or rate-limit dependency is unavailable. Retry with backoff; the request is rejected rather than processed without protection. |
Ámbitos y privilegio mínimo
Cada clave está limitada a los ámbitos seleccionados. Use claves de solo lectura siempre que sea posible y una clave distinta para cada integración. Un ámbito de escritura no concede automáticamente el ámbito de lectura correspondiente.
assistants:read
assistants:write
analytics:read
artifacts:read
artifacts:write
billing:read
bookings:read
bookings:write
chat:write
connectors:read
connectors:write
conversations:read
conversations:write
knowledge:read
knowledge:write
leads:read
leads:write
telephony:read
telephony:write
widget:writeLímite de claves API
Cada clave de desarrollador admite 300 solicitudes por minuto móvil de forma predeterminada y atómica entre instancias. Un rechazo devuelve 429; espera al reinicio antes de reintentar.
2. Ciclo de vida del asistente (creación)
GET /api/assistants
Lista de asistentes
Obtiene una lista de todos los asistentes asociados con el espacio de trabajo de la clave API.
Crear un asistente
POST /api/assistants
Crea un nuevo asistente con todas las configuraciones básicas.
{
"businessName": "Acme Corp",
"businessUrl": "https://acme.com",
"knowledgeBaseType": "both",
"knowledgeBaseUrl": "https://acme.com/help",
"knowledgeBaseText": "Raw text content of a document...",
"knowledgeBaseFileName": "company_handbook.pdf",
"language": "en",
"isMultiLanguage": false,
"tonePersonality": "professional",
"isCustomPersonality": false,
"supportEmail": "[email protected]",
"maxPages": 5,
"maxDepth": 2,
"welcomeMessageDelay": 2
}| Parámetro | Tipo | Requerido | Descripción |
|---|---|---|---|
businessName | Cadena | Sí | Nombre de la empresa (2-100 caracteres). |
businessUrl | Cadena | Sí | URL válida del sitio web empresarial (máximo 500 caracteres). |
knowledgeBaseType | enumeración | Sí | Uno de: "url", "document", "both", "none". |
knowledgeBaseUrl | Cadena | No | Se debe proporcionar si el tipo es "url" o "both". |
knowledgeBaseText | Cadena | No | Texto sin formato si el tipo es "document" o "both". |
knowledgeBaseFileName | Cadena | No | Nombre del archivo cargado si proporciona texto. |
language | Cadena | Sí | Language code (e.g., "en", "es"). |
isMultiLanguage | Booleano | No | Habilitar la traducción automática. Por defecto "falso". |
tonePersonality | Cadena | Sí | Por ejemplo, "professional", "friendly". Máximo 100 caracteres. |
isCustomPersonality | Booleano | No | Habilitar tono personalizado. Por defecto "falso". |
customPersonalityDescription | Cadena | No | Instrucciones de tono personalizadas si están habilitadas (máximo 2000 caracteres). |
additionalInstructions | Cadena | No | Instrucciones principales (máximo 10000 caracteres). |
supportEmail | Cadena | Sí | Dirección de correo electrónico válida para escalamiento. |
maxPages | Número | No | Páginas para rastrear. Mín. 1, Máx. 100. Predeterminado "5". |
maxDepth | Número | No | Profundidad de rastreo. Mín. 1, Máx. 20. Predeterminado "2". |
welcomeMessageDelay | Número | No | Retraso en segundos antes del saludo. Mín. 0, Máx. 6. Predeterminado 2. |
Eliminar asistente
DELETE /api/assistants/:id
Elimina permanentemente el asistente y elimina en cascada todos sus nodos de conocimiento y su historial. No se requiere carga útil.
Creation validation and quota safety
| Input | Contract |
|---|---|
knowledgeBaseUrl | For url or both: 1–20 comma-separated public HTTP(S) URLs, with at most 2,000 characters in total. |
knowledgeBaseText | Required for document or both; maximum 2,000,000 characters. |
knowledgeBaseFileName | Optional source label; maximum 255 characters. |
maxPages / maxDepth | Requested values are bounded by both the documented hard limits and the workspace plan. |
Creation allowance is reserved atomically before insertion, so concurrent requests cannot exceed the monthly quota. Database insertion failures refund that reservation. A created assistant starts inactive in developer mode; call the setup endpoint and wait for its successful terminal event before publishing it.
3. Asistente de análisis y estadísticas
Inmediatamente después de la creación y el uso, puede recuperar mediante programación las métricas de rendimiento del asistente.
GET /api/analytics/overview?assistantId=uuid&range=30
Obtenga estadísticas de uso, mensajes totales, clientes potenciales capturados y métricas generales de participación para el asistente especificado. El parámetro "rango" es opcional (número de días, mínimo 7, máximo 365, predeterminado 30).
Respuesta esperada
{
"totalConversations": 1245,
"totalMessages": 8420,
"totalLeads": 156,
"totalBookings": 42,
"satisfactionRate": 94,
"avgMessagesPerSession": 6.7,
"avgSessionsPerDay": 41.5,
"liveNow": 3,
"onlineNow": 12,
"dailySeries": [
{
"date": "2026-07-15",
"conversations": 45,
"messages": 310,
"leads": 5,
"bookings": 2
}
],
"agentStats": [
{
"name": "Jane Doe",
"messagesSent": 120,
"csat": 98
}
]
}| Propiedad | Tipo | Descripción |
|---|---|---|
totalConversations | Número | Número total de sesiones de chat manejadas por el asistente. |
totalMessages | Número | Número total de mensajes (usuario + IA) enviados en todas las conversaciones. |
totalLeads | Número | Número total de clientes potenciales únicos (nombre, correo electrónico, teléfono) extraídos. |
totalBookings | Número | Número total de citas del calendario reservadas correctamente. |
satisfactionRate | Número | Porcentaje (0-100) de calificaciones de comentarios positivos sobre el total de calificaciones. |
avgMessagesPerSession | Número | Número medio de mensajes intercambiados por conversación. |
avgSessionsPerDay | Número | Número promedio de conversaciones por día dentro del rango solicitado. |
liveNow | Número | Número de conversaciones activas asumidas actualmente por un agente humano. |
onlineNow | Número | Número de usuarios que chatean activamente con la IA en los últimos 2 minutos. |
dailySeries | Formación | Matriz de objetos diarios que contienen recuentos de "conversaciones", "mensajes", "clientes potenciales" y "reservas" por fecha. |
agentStats | Formación | Métricas de rendimiento para agentes humanos, incluidos messagesSent y csat (puntuación de satisfacción del cliente). |
4. Conocimiento y formación
Una vez creado un asistente, gestionas su cerebro a través de "Nodos de conocimiento". Cada nodo representa una porción de datos (una URL rastreada, un documento cargado o un fragmento de texto manual).
Gestión de nodos de conocimiento
GET /api/assistants/:id/nodes: enumera todos los nodos de conocimiento para este asistente.
POST /api/assistants/:id/nodes - Inyecta manualmente un nuevo bloque de conocimiento.
{
"title": "Return Policy",
"refined_content": "We offer a 30-day return policy for all unused items...",
"type": "text",
"metadata": {}
}PATCH /api/assistants/:id/nodes/:nodeId: modifica el contenido de un nodo existente o alterna su estado activo.
{
"title": "Updated Return Policy",
"refined_content": "We offer a 60-day return policy now...",
"is_active": true
}DELETE /api/assistants/:id/nodes/:nodeId - Elimina un bloque de conocimiento por completo.
POST /api/assistants/:id/nodes/:nodeId/re-crawl: obliga al raspador a volver a rastrear la URL asociada con este nodo y actualizar su contenido. Carga útil: {}.
Entrenamiento de IA
POST /api/assistants/:id/train: compila todos los nodos de conocimiento is_active y utiliza un orquestador de IA para sintetizar dinámicamente un nuevo mensaje maestro del sistema. Carga útil: {}.
Upload, crawl, and index consistency
| Operation | Limits and guarantees |
|---|---|
| Manual node | Title: 1–200 characters; content: 1–200,000 characters; metadata: object up to 20,000 serialized characters. |
| File upload | PNG, JPEG, WebP, PDF, DOCX, TXT, or Markdown; maximum 10 MB. Failed extraction creates a disabled repairable node and returns vector_sync_pending: true. |
| Deep crawl | maxPages is a positive integer capped by the plan (100 hard maximum); depth is capped at 20. Only public HTTP(S) destinations are allowed, including redirects and browser subrequests. |
| Enable / disable | Disabled nodes are removed from the vector index and are also filtered at retrieval time. Re-enable or edit an active node to rebuild its vectors. |
vector_sync_pending response means the record was saved but is not yet guaranteed searchable; call the sync endpoint or retry the edit.POST /api/knowledge/urls is retained only to return an explicit 410 Gone; it never stores data. Migrate to POST /api/assistants/:id/nodes/deep-crawl.5. Apariencia y comportamiento del widget
Todos los campos PATCH aceptados, valores reales, límites y reglas del plan.
PATCH /api/assistants/:id/widget-config
Envía solo los campos que quieras cambiar. La API rechaza claves desconocidas y datos anidados inválidos.
{
"designPreset": "corporate-soft",
"primaryColor": "#1972F5",
"theme": "dark",
"bubbleStyle": "branded-drawer",
"bubbleText": "Talk to our team",
"welcomeMessages": [
{
"text": "Hello! How can I help?",
"delay": 1.5
}
],
"welcomeSuggestions": [
"View pricing",
"Book a demo"
],
"pageVisibility": {
"mode": "exclude",
"paths": [
"/checkout/*"
]
},
"voiceEnabled": true,
"voiceName": "Aoede",
"copilotEnabled": true,
"gdprConsentEnabled": true,
"privacyPolicyUrl": "https://example.com/privacy"
}| Campo | Tipo / límites | Predeterminado | Efecto | Regla del plan |
|---|---|---|---|---|
primaryColor | hex color | #000000 | Código de color hexadecimal (por ejemplo, "#000000"). | — |
designPreset | enum | default | Visual system: default, legacy, corporate, corporate-soft, editorial. | — |
position | enum | bottom-right | "bottom-right", "bottom-left", "top-right", "top-left". | — |
theme | enum | light | "light" u "dark". | — |
fontFamily | enum | default | "default" (Inter) o "inherit". | — |
bubbleStyle | enum | circle | "circle", "bar", "drawer", "branded-circle", "branded-bar", "branded-drawer". | Branded launcher styles require custom-branding access. |
bubbleText | string (1–80) | Chat with us | Texto que se mostrará junto a la burbuja (para estilos de barra/cajón). | — |
customLogoUrl | HTTP(S) URL or null | null | URL a la imagen del logotipo del encabezado personalizado. | Requires custom-branding access. Prefer HTTPS or the widget-logo upload endpoint. |
title | string (1–50) | business name | El título en el encabezado del widget. | — |
headerSubtitle | string (0–100) | We typically reply instantly | Subtítulo en el encabezado del widget. | — |
welcomeMessage | string (0–300) | Hi! How can I help you today? | El mensaje de saludo inicial. | — |
welcomeMessages | array (1–5) | one greeting | Ordered greeting objects with text (1–300) and delay in seconds (0–10). | — |
welcomeMessageDelay | number (0–10) | 2 | Retraso en segundos antes del saludo. | — |
welcomeSuggestions | string[] (max 3) | [] | Conjunto de cadenas para chips de respuesta rápida iniciales. | — |
inputPlaceholder | string (1–100) | Type your message... | Texto de marcador de posición para la entrada del mensaje. | — |
language | language code | assistant language | Código de idioma del widget (por ejemplo, "en", "fr"). | — |
showBranding | boolean | true | Show the Powered by Chirps attribution. | Plans without branding removal always force true. |
voiceEnabled | boolean | true | Habilitar llamadas de voz. | Plans without voice access always force false. |
voiceModel | string | platform default | Realtime voice model identifier. Normally leave unchanged so Chirps can use the supported platform model. | — |
voiceName | enum | Fenrir | La identidad de voz para respuestas de audio. Vea las voces disponibles a continuación. | — |
fileUploadEnabled | boolean | true | Permitir a los usuarios cargar archivos adjuntos. | Plans without file uploads always force false. |
dictationEnabled | boolean | true | Habilite el dictado de voz (voz a texto). | — |
copilotEnabled | boolean | plan default | Allow the DOM-navigation Copilot experience. | Plans without Copilot always force false. |
pageVisibility | object | { mode: all, paths: [] } | Determina en qué páginas aparece el widget (mode, paths). | — |
humanizerEnabled | boolean | true | Apply the conversational response-style pass. | — |
promptInjectionProtectionEnabled | boolean | true | Screen visitor and uploaded-file prompt injection attempts and keep lower-trust content from overriding assistant instructions. | — |
rateLimitEnabled | boolean | true | Habilite la limitación de la velocidad del chat. Verdadero predeterminado. | — |
rateLimitMaxMessages | integer (1–500) | 30 | Máximo de mensajes en ventana. Por defecto 30. | — |
rateLimitTimeWindow | integer minutes (1–1440) | 60 | Ventana de tiempo en minutos. Por defecto 60. | — |
privacyPolicyUrl | HTTP(S) URL | empty | URL a su política de privacidad. | — |
gdprConsentEnabled | boolean | false | Show the compact chat privacy notice before the visitor sends data. | — |
gdprDataMaskingEnabled | boolean | false | Enmascare la PII antes de guardar. Por defecto es falso. | — |
cookieConsentEnabled | boolean | false | Enable widget cookie preferences and consent UI. | — |
cookieConsentAnalyticsEnabled | boolean | true | Offer optional analytics in cookie preferences. Analytics events remain blocked until the visitor affirmatively consents. | — |
Coincidencia de páginas
Usa rutas exactas como /pricing o /* para descendientes como /docs/*. include muestra coincidencias, exclude las oculta y all ignora las rutas.
Voces disponibles
Zephyr, Aoede, Kore, Leda, Callirrhoe, Despina, Erinome, Laomedeia, Achernar, Pulcherrima, Gacrux, Algenib, Sulafat, Puck, Charon, Fenrir, Orus, Enceladus, Iapetus, Umbriel, Algieba, Autonoe, Rasalgethi, Alnilam, Schedar, Sadachbia, Achird, Zubenelgenubi, Sadaltager
GET /api/assistants/:id/widget-config without an API key. That read is intentionally origin-bound to the authorized business domain in production mode and returns plan-normalized public configuration. It is not a server-to-server developer endpoint; never treat it as a way to read private assistant settings.6. Artefactos interactivos
Configuración completa para formularios, reservas, tarjetas, CSAT y herramientas personalizadas.
GET /api/assistants/:id/artifacts · PUT /api/assistants/:id/artifacts · PATCH /api/assistants/:id/artifacts
Los artefactos usan llamadas a herramientas. El modelo llama la herramienta habilitada y Chirps renderiza la interfaz; no envíes cadenas {{ARTIFACT: ...}}.
{
"form": {
"enabled": true,
"title": "Request a quote",
"description": "Collect the details needed for a quote.",
"triggerRules": "When a visitor explicitly asks for a quote.",
"fields": [
{
"key": "name",
"label": "Full name",
"type": "text",
"required": true,
"placeholder": "Jane Doe"
},
{
"key": "email",
"label": "Work email",
"type": "email",
"required": true
}
],
"submitLabel": "Request quote"
},
"booking": {
"enabled": true,
"title": "Book a consultation",
"description": "Choose an available time.",
"triggerRules": "When a visitor asks to book a meeting.",
"services_enabled": false,
"meetings_enabled": true,
"requiresScheduling": true,
"timezone": "Europe/Paris",
"slotDuration": 30,
"bufferMinutes": 10,
"workingHours": {
"monday": {
"enabled": true,
"start": "09:00",
"end": "17:00"
},
"tuesday": {
"enabled": true,
"start": "09:00",
"end": "17:00"
},
"wednesday": {
"enabled": true,
"start": "09:00",
"end": "17:00"
},
"thursday": {
"enabled": true,
"start": "09:00",
"end": "17:00"
},
"friday": {
"enabled": true,
"start": "09:00",
"end": "17:00"
},
"saturday": {
"enabled": false,
"start": "10:00",
"end": "14:00"
},
"sunday": {
"enabled": false,
"start": "10:00",
"end": "14:00"
}
},
"blockedDates": [
"2026-12-25"
],
"meeting_intake_fields": [
{
"key": "email",
"label": "Email",
"type": "email",
"required": true
}
],
"submitLabel": "Book meeting"
},
"card": {
"enabled": false,
"ctaLabel": "View details",
"ctaUrl": "",
"description": "",
"triggerRules": ""
},
"csat_survey": {
"enabled": true,
"title": "How was your experience?",
"description": "One-click feedback.",
"triggerRules": "Only after the request is resolved."
},
"custom": []
}| Sección | Propiedades aceptadas | Comportamiento |
|---|---|---|
form | enabled, title, description, triggerRules, fields, submitLabel | Lead capture and structured intake through show_form. |
booking | enabled, title, description, triggerRules, services_enabled, meetings_enabled, requiresScheduling, timezone, slotDuration, bufferMinutes, workingHours, blockedDates, categories, services, meeting_intake_fields, submitLabel | Meeting or service scheduling through show_booking; supplied values can be prefilled and exact requested slots are verified. |
card | enabled, ctaLabel, ctaUrl, description, triggerRules | Transactional rich-card behavior when verified product data exists. |
csat_survey | enabled, title, description, triggerRules | Thumbs-up/down feedback through show_csat_survey. |
custom | Array of enabled, name, type, description, triggerRules, schema, isCustom | Plan-gated custom tool-backed artifacts. |
Field schema
| Campo | Tipo / límites | Efecto |
|---|---|---|
key | string | Stable machine key used by prefilled_data and requested_fields. |
label | string | Visitor-facing label. |
type | enum | text, email, tel, textarea, number, date, url, dropdown, radio, checkbox, slider, select, or location. |
required | boolean | Blocks submission until a valid value is supplied. |
placeholder | string (max 200) | Optional hint shown inside the control. |
options | string[] | Choices for dropdown, radio, and select controls. |
min, max, step | number | Numeric and slider bounds. |
geo_scope | object | Location boundary: worldwide, continent, country, state, city, or custom; optional value and map bounds. |
Booking service schema
| Campo | Tipo / límites | Efecto |
|---|---|---|
id, name, description | string | Stable service identity and visitor-facing copy. |
duration | minutes | Service duration; the configured slot duration is the fallback. |
category, price | string | Optional filtering and display metadata. |
routing.type | enum | virtual, physical, or phone. |
routing.platform | enum | google_meet, teams, or custom for virtual services. |
routing.link, routing.address | string | Destination appropriate to the selected routing type. |
intake_fields | field[] | Service-specific information requested during booking. |
Validation limits and scheduling rules
| Campo | Tipo / límites | Efecto |
|---|---|---|
fields, meeting_intake_fields, intake_fields | max 50 each | Every field needs a unique machine key, label, and supported type. |
services / categories | max 100 each | Service IDs should remain stable after clients begin storing them. |
slotDuration | integer 5–480 minutes | Length of generated calendar slots. |
bufferMinutes | integer 0–1440 minutes | Unavailable gap inserted around bookings. |
timezone | IANA time-zone name | Business schedule zone, for example Europe/Paris; visitor times are converted for display and calendar invitations. |
workingHours | seven day objects | Each enabled day uses 24-hour HH:mm and must end after it starts. |
blockedDates | YYYY-MM-DD[] (max 366) | Dates unavailable in the business time zone. |
custom | max 20 | Custom tools are plan-gated; names and types are required. |
Tool-call prefill behavior
| Campo | Tipo / límites | Efecto |
|---|---|---|
prefilled_data | object | Values already learned in chat, keyed by configured field key. |
requested_fields | string[] | Show only the configured fields relevant to this intent. |
mode | meeting or service | Select the general meeting flow or a configured service flow. |
selected_service_id | string | Preselect a configured service; never invent an ID. |
requested_categories | string[] | Restrict the visible service list to configured categories. |
preferred_start_time_iso | ISO-8601 | Ask the widget to verify one visitor-requested instant before showing approval. |
artifacts array; streaming responses emit event: artifacts with { artifacts: [...] }. Chirps also keeps compatibility tags in message text for existing widgets and stored history. New clients should consume the structured field/event and treat message text as display copy.7. Conectores y herramientas
Descubre esquemas, almacena credenciales de forma segura y activa solo las herramientas necesarias.
Start with GET /api/marketplace/connectors. Its provider definitions are the source of truth for credential fields, configuration fields, available tools, defaults, and required values; this keeps custom and future providers discoverable without a documentation release.
{
"provider": "shopify",
"name": "Shopify",
"credentials": {}
}- Install the workspace connector record with
POST /api/assistants/:id/connectors;credentialsmust be omitted or{}. - Read its exact field schema from
GET /api/marketplace/connectorsand activate it withPOST /api/assistants/:id/connectors/:connectorId/activate. - Send
configValues, optionalenabledTools, and optionalinstructions. Chirps verifies non-custom connectors and discovers the tools before saving the integration. - Rotate secrets by calling the activation endpoint again.
PUTonly renames a named Custom API. - Use
DELETE /api/assistants/:id/connectorswith{ connectorId }to disable it for one assistant. Use the nestedDELETE .../:connectorIdonly to permanently remove it from the workspace and every assistant.
| Campo | Tipo / límites | Efecto |
|---|---|---|
configValues | object (max 100 scalar values) | Exact keys from the marketplace schema. Values are bounded and secrets are write-only. |
enabledTools | string[] (max 200) | Optional allow-list of tools discovered from the verified connector. |
instructions | string (max 10,000) | Assistant-specific constraints for tool use. |
name | string (max 120) | Optional rename during activation, supported only for named Custom APIs. |
8. Integración e implementación
Una vez que su asistente esté configurado y capacitado, tiene dos formas principales de implementarlo:
Opción A: Web Embed (frontend)
La forma más sencilla de integrar el asistente en un sitio web estándar (WordPress, Shopify, React, etc.). El código de inserción es puramente determinista. No necesita un punto final para recuperarlo. Simplemente coloque esto en el <head> de su sitio:
<script>
window.chirpsConfig = { assistantId: "YOUR_ASSISTANT_ID" };
</script>
<script src="https://chirps.cc/embed.js" async></script>Opción B: Integraciones sin cabeza (Backend/CRM/Bots)
Si está creando un cliente personalizado (como un bot de Discord, una integración de Telegram o una aplicación nativa de iOS), NO utilizará Web Embed. En su lugar, interactuará directamente con el punto final /api/chat.
POST /api/chat o /api/chat?stream=true
Importante: las llamadas headless y de servidor a servidor deben incluir Authorization: Bearer <YOUR_CHIRPS_API_KEY>. Solo el widget instalado en el navegador usa el flujo público vinculado al origen. Nunca incluya una clave API en JavaScript del frontend.
{
"assistantId": "123e4567-e89b-12d3-a456-426614174000",
"sessionId": "unique-session-id-for-user",
"conversationId": "optional-uuid",
"message": "Hello, I need help with my billing."
}*(También admite multipart/form-data con un campo file para archivos adjuntos si fileUploadEnabled es verdadero).*
| Parámetro | Tipo | Requerido | Descripción |
|---|---|---|---|
assistantId | Cadena | Sí | El UUID del asistente. |
sessionId | Cadena | Sí | Tú generas esto. Un identificador único de tu propio sistema para agrupar el historial de chat (por ejemplo, un ID de usuario de Discord, un ID de chat de Telegram o un UUID aleatorio). |
message | Cadena | Sí | El contenido de texto del mensaje (máximo 5000 caracteres). |
conversationId | Cadena | No | El UUID de la conversación (devuelto en su primera solicitud). |
id | Cadena | No | ID de mensaje del lado del cliente opcional para evitar la deduplicación. |
Modo 1: Respuesta JSON estándar (predeterminada)
Al enviar una solicitud POST a /api/chat (sin el parámetro de transmisión), espera la respuesta AI completa y recibe un objeto JSON estándar.
{
"message": "Here is the information you requested...",
"conversationId": "uuid-of-conversation",
"messageId": "uuid-of-message"
}*(Si se devuelve is_active_agent: true, un humano se ha hecho cargo del chat y message será null.)*
Modo 2: Transmisión de eventos enviados por el servidor (?stream=true)
Al agregar ?stream=true a la URL, recibirá una transmisión de eventos enviados por el servidor (SSE) en tiempo real. Su código debe escuchar estos tipos de eventos específicos:
- `event: token`: Contiene
{"text": "chunk"}. Se dispara por cada fragmento del texto de respuesta de la IA. - `event: status`: Contiene
{"text": "Searching knowledge base..."}. Representa los estados de ejecución de la herramienta backend. - `event: done`: Contiene
{"messageId": "uuid", "conversationId": "uuid", "message": "full text"}. Despedido cuando la generación está completamente terminada. - `event: error`: Contiene
{"error": "Error message"}. Despedido si ocurren límites de tarifas o errores.
Puntos finales de adquisición en vivo
GET /api/chat/sessions
Recuperar sesiones históricas.
POST /api/chat/toggle-agent
Pausa la IA para que el hombre tome el control. Carga útil: { "sessionId": "...", "isActive": true }
POST /api/chat/agent-message
Enviar mensaje humano. Carga útil: { "sessionId": "...", "message": "..." }
Complete chat response contract
{
"message": "I've opened the booking calendar for you.",
"messageId": "uuid",
"conversationId": "uuid",
"artifacts": [
{
"type": "booking",
"title": "Book a consultation"
}
],
"sources": []
}A human takeover returns { message: null, conversationId, is_active_agent: true }. A streaming request can therefore return JSON before an SSE stream begins; check the response Content-Type.
Complete SSE event reference
| Event | Payload and behavior |
|---|---|
token | { text } — committed assistant text chunk. |
status | { text } — tool or retrieval progress for user-facing status UI. |
artifacts | { artifacts: [...] } — structured tool-generated UI payloads. |
sources | { sources, tag } — structured citations when enhanced streaming is enabled. |
provisional | { text } — temporary pre-tool text with X-Chirps-Stream-Version: 2. |
reset | {} — discard accumulated provisional text. |
commit | {} — commit accumulated provisional text. |
done | { messageId, conversationId, message } — authoritative final message. |
error | { error } — terminal generation error. |
X-Chirps-Stream-Version: 2 to receive provisional/reset/commit and structured source events. Clients that do not implement those events should omit the header and rely on token, artifacts, done, and error.9. Configuración avanzada del asistente
PATCH /api/assistants/:id
Actualizar la configuración principal
Modifique la configuración principal, la personalidad y los límites de raspado del asistente.
{
"business_name": "Acme Corp",
"business_url": "acme.com",
"business_description": "We sell anvils.",
"system_prompt": "You are a helpful assistant.",
"language": "en",
"tone_personality": "Friendly",
"support_email": "[email protected]",
"additional_instructions": "Never mention the Roadrunner.",
"is_multi_language": true,
"is_dev_mode": false,
"is_active": true,
"max_pages": 15,
"max_depth": 2,
"widget_config_merge": {
"rateLimitEnabled": true
}
}*Nota: Todos los campos son opcionales. Envíe únicamente los campos que desee actualizar.*
Eliminar asistente
DELETE /api/assistants/:id
Elimina permanentemente el asistente y la eliminación en cascada a todos los nodos de conocimiento, conversaciones y mensajes. Si el asistente nunca estuvo completamente configurado, se reembolsa la cuota de creación mensual.
10. Telefonía y Voz
GET /api/phone-numbers - Lista de números disponibles.
POST /api/phone-numbers/:subscriptionId/assign assigns an already-purchased Chirps phone subscription to an assistant. Send { "assistantId": "uuid" }; send { "assistantId": null } to unassign it. This endpoint does not purchase or provision a new number.
POST /api/assistants/:id/outbound - Activar llamada saliente. Carga útil: { "phoneNumber": "+123...", "callReason": "Confirm the requested appointment", "conversationId": "optional-uuid" }
11. Extracción de clientes potenciales
GET /api/leads?assistantId=uuid&page=1&limit=50&status=new: obtenga clientes potenciales estructurados y paginados que la IA extrajo durante las conversaciones.
GET /api/leads?id=leadId: obtiene detalles de un único cliente potencial, incluida la transcripción completa de la conversación.
Public lead response
Lead objects contain id, assistant_id, conversation_id, session_id, name, email, phone, status, notes, artifact_id, ai_score, ai_summary, form_data, created_at, and the assistant business name. Internal voice-confirmation/idempotency identifiers are never returned.
12. Reservas y Calendario
GET /api/bookings?assistantId=uuid&start=ISO-8601&end=ISO-8601: recupera citas del calendario programadas por el asistente, opcionalmente filtradas por fecha.
GET /api/bookings?id=bookingId: recupera los detalles de una sola reserva, incluida la transcripción de la conversación.
DELETE /api/bookings/cancel?id=bookingId - Cancela una reserva activa. Añada &silent=true solo si su integración debe omitir intencionadamente el correo de cancelación de respaldo de Chirps.
POST /api/bookings/reschedule - Ajustar una reserva. Carga útil: { "bookingId": "uuid", "newStartTime": "ISO-8601", "newEndTime": "ISO-8601" }
Public booking response and time zones
Booking objects contain the public appointment, guest, status, notes, and timestamp fields plus business_timezone. Times are ISO-8601 instants; format them in the viewer's time zone while preserving the returned business zone for schedule context. Internal confirmation IDs, provider calendar-event IDs, and database range columns are omitted.
13. Uso de cuenta y facturación
GET /api/billing/usageón/uso
Recupere el uso del ciclo de facturación del espacio de trabajo, los límites del plan de suscripción y el recuento total de asistentes. Nota: Cuando se utiliza una clave API, la solicitud se limita automáticamente al espacio de trabajo de la clave API; no es necesario proporcionar un "teamId".
Respuesta (`200 OK`):
{
"planName": "Pro",
"periodStr": "2023-10-01",
"assistantCount": 3,
"usage": {
"message_count": 1450,
"harvest_count": 12,
"recrawl_count": 5,
"train_count": 2,
"assistants_created_count": 1,
"voice_minutes_used": 0,
"sms_count": 0,
"email_count": 0,
"whatsapp_count": 0
},
"limits": {
"messages": 5000,
"assistants": 5,
"training": 50,
"recrawls": 20
},
"workspaceOwnerId": "uuid"
}14. Catálogo completo de endpoints
La superficie revisada y compatible con claves API. Las rutas y propiedades JSON nunca se traducen.
Qué pertenece a la API pública para desarrolladores
Estas rutas aceptan una clave API de Chirps con ámbitos y aplican el límite de su espacio de trabajo. Se excluyen intencionadamente las rutas de facturación/OAuth del panel, callbacks del widget, webhooks de proveedores, cron y MCP interno.
id de cliente estable para evitar duplicados. No reintente automáticamente otras escrituras salvo que la respuesta indique que es seguro. 402 indica cuota agotada, 429 limitación y 5xx puede ser transitorio.Asistentes
| Método | Ruta | Ámbito | Solicitud | Resultado correcto |
|---|---|---|---|---|
GET | /api/assistants | assistants:read | — | Assistant array; credential fields omitted |
POST | /api/assistants | assistants:write | Assistant creation JSON | Created assistant and setup identifiers |
GET | /api/assistants/:id | assistants:read | — | Assistant configuration; secrets omitted |
PATCH | /api/assistants/:id | assistants:write | Supported fields only | Updated assistant |
DELETE | /api/assistants/:id | assistants:write | — | Deletion confirmation |
GET | /api/assistants/:id/setup | assistants:read | — | Setup and crawl status |
POST | /api/assistants/:id/setup | assistants:write | Empty body | SSE setup progress stream |
GET | /api/analytics/overview?assistantId=:id&range=30 | analytics:read | Query: range 7–365 | Engagement, lead, booking and agent metrics |
Conocimiento y entrenamiento
| Método | Ruta | Ámbito | Solicitud | Resultado correcto |
|---|---|---|---|---|
GET | /api/assistants/:id/nodes | knowledge:read | — | Knowledge node array |
POST | /api/assistants/:id/nodes | knowledge:write | { title, refined_content, type?, metadata? } | Stored and vectorized node |
PATCH | /api/assistants/:id/nodes/:nodeId | knowledge:write | { title?, refined_content?, is_active? } | Updated and re-vectorized node |
DELETE | /api/assistants/:id/nodes/:nodeId | knowledge:write | — | Node deletion confirmation |
POST | /api/assistants/:id/nodes/:nodeId/re-crawl | knowledge:write | Empty body | Refreshed URL node |
POST | /api/assistants/:id/nodes/upload | knowledge:write | multipart/form-data: file, title? | Extracted knowledge node |
POST | /api/assistants/:id/nodes/deep-crawl | knowledge:write | { maxPages? } | SSE crawl progress stream |
POST | /api/assistants/:id/nodes/sync | knowledge:write | Empty body | Vector store synchronization result |
POST | /api/assistants/:id/train | knowledge:write | Empty body | Compiled assistant prompt |
POST | /api/assistants/:id/harvest | knowledge:write | Empty body | Conversation insights added to knowledge |
POST | /api/knowledge/urls | knowledge:write | Deprecated | Always returns 410 with the assistant-scoped deep-crawl replacement path |
Widget, artefactos y conectores
| Método | Ruta | Ámbito | Solicitud | Resultado correcto |
|---|---|---|---|---|
PATCH | /api/assistants/:id/widget-config | widget:write | Partial widget configuration | Normalized widget configuration |
POST | /api/assistants/:id/widget-logo | widget:write | multipart/form-data: file (PNG/JPEG/WebP, max 2 MB) | Public logo URL |
GET | /api/assistants/:id/artifacts | artifacts:read | — | Form, booking, card and CSAT configuration |
PUT | /api/assistants/:id/artifacts | artifacts:write | Complete artifact configuration | Normalized configuration |
PATCH | /api/assistants/:id/artifacts | artifacts:write | Partial artifact configuration | Merged normalized configuration |
GET | /api/marketplace/connectors | connectors:read | — | Installable connector definitions; no credentials |
GET | /api/assistants/:id/connectors | connectors:read | — | Workspace connectors and assistant integrations |
POST | /api/assistants/:id/connectors | connectors:write | { provider, name, credentials?: {} } | Installed connector record; no operational access yet |
PUT | /api/assistants/:id/connectors/:connectorId | connectors:write | { name } (named custom APIs only) | Renamed connector; credentials omitted |
DELETE | /api/assistants/:id/connectors | connectors:write | { connectorId } | Connector disabled for this assistant only |
DELETE | /api/assistants/:id/connectors/:connectorId | connectors:write | — | Workspace connector and all assistant integrations deleted |
POST | /api/assistants/:id/connectors/:connectorId/activate | connectors:write | { configValues, enabledTools?, instructions?, name? } | Activated integration and tool list |
Conversaciones, leads y reservas
| Método | Ruta | Ámbito | Solicitud | Resultado correcto |
|---|---|---|---|---|
POST | /api/chat or /api/chat?stream=true | chat:write | { assistantId, sessionId, message, conversationId?, id? } | JSON reply with artifacts/sources or SSE token/artifacts/status/done events |
GET | /api/chat/sessions?assistantId=:id | conversations:read | — | 20 most recent session summaries |
GET | /api/assistants/:id/conversations?limit=20&status=active | conversations:read | Query: limit 1–50, status optional | Conversation summaries |
DELETE | /api/assistants/:id/conversations | conversations:write | { conversationIds: [uuid] } (max 100) | Deletion confirmation |
POST | /api/chat/toggle-agent | conversations:write | { sessionId, isActive } | Takeover state |
POST | /api/chat/agent-message | conversations:write | { sessionId, message } | Stored human-agent message |
POST | /api/chat/typing | conversations:write | { assistantId, sessionId, isTyping } | Typing-state confirmation |
POST | /api/chat/followup-draft | conversations:write | { conversationId|leadId, assistantId?, channel? } | AI-generated draft; consumes AI-message usage |
POST | /api/chat/conversation-followup | conversations:write | { conversationId|leadId, channel, recipient, subject?, message } | Dispatched follow-up result |
GET | /api/leads | leads:read | Query: id, or assistantId with page, limit, status | Lead detail with transcript or paginated leads; internal confirmation identifiers omitted |
POST | /api/leads | artifacts:write | Artifact submission JSON | Captured lead/booking result |
PATCH | /api/leads | leads:write | { leadId, status?, notes? } | Updated lead |
DELETE | /api/leads | leads:write | { leadId } or { leadIds: [uuid] } | Deletion count |
GET | /api/bookings | bookings:read | Query: id, or assistantId with start and end | Booking detail or booking array; provider and idempotency identifiers omitted |
DELETE | /api/bookings/cancel?id=:id | bookings:write | Query: silent=true optional | Cancellation and calendar-sync state |
POST | /api/bookings/reschedule | bookings:write | { bookingId, newStartTime, newEndTime } | Updated booking or available alternatives |
Telefonía y cuenta
| Método | Ruta | Ámbito | Solicitud | Resultado correcto |
|---|---|---|---|---|
GET | /api/phone-numbers | telephony:read | — | Numbers and assignable assistants in this workspace |
POST | /api/phone-numbers/:subscriptionId/assign | telephony:write | { assistantId } or { assistantId: null } | Routing update confirmation |
POST | /api/assistants/:id/outbound | telephony:write | { phoneNumber, callReason, conversationId? } | Provider call SID and conversation ID |
GET | /api/billing/usage | billing:read | — | Workspace plan, limits and current usage |
GET | /api/metadata?url=:httpsUrl | artifacts:read | Query: public HTTP(S) URL | Bounded page title, description and image metadata |
Inicia tu asistente
en 10 minutos.
Regístrese, capacítese en su sitio, personalice alertas e insértelas en su sitio web.