¡Todavía estamos construyendo cosas aquí! Puedes notar algunos bordes ásperos mientras trabajamos en mejoras. Ayúdanos a mejorar reportando errores aquí.

Referencia de API

Referencia completa de API para la integración con la plataforma Assistant. Incluye autenticación, endpoints, esquemas de solicitud/respuesta, y ejemplos de código prácticos.

Autenticación

La API admite dos métodos de autenticación:

  • Autenticación con clave API: Use los encabezados X-API-Key y X-API-Secret para acceso directo a la API
  • Autenticación con token JWT: Use tokens Bearer obtenidos del endpoint de token widget para solicitudes basadas en navegador

Endpoint de Token Widget

Genere tokens JWT de corta duración para autenticación de widgets. Este endpoint permite a los widgets obtener tokens seguros usando solo el client_id, evitando la necesidad de exponer el client_secret en entornos de navegador.

JSONrequest.json
{"client_id": "YOUR_CLIENT_ID"}

Respuesta:

JSONresponse.json
{  "token": "eyJ...",  "expires_in": 3600,  "token_type": "Bearer"}

Limitación de tasa

Las solicitudes de API están limitadas a 1000 por hora por organización. La información de limitación de tasa se incluye en los encabezados de respuesta.

Manejo de errores

Todos los errores de API devuelven respuestas JSON estructuradas con códigos de estado, detalles de error y campos de datos opcionales.

JSONerror.json
{  "status": "error",  "status_code": 401,  "detail": "Authentication required - ...",  "data": null}

Endpoints de API

Asistentes

Gestionar personas de asistente de IA con configuraciones personalizadas.

Listar asistentes

GNU Bashlist-assistants.sh
curl -X GET https://app.companin.tech/api/v1/assistants/ \  -H "X-API-Key: YOUR_CLIENT_ID" \  -H "X-API-Secret: YOUR_CLIENT_SECRET"

Crear asistente

GNU Bashcreate-assistant.sh
curl -X POST https://app.companin.tech/api/v1/assistants/ \  -H "X-API-Key: YOUR_CLIENT_ID" \  -H "X-API-Secret: YOUR_CLIENT_SECRET" \  -H "Content-Type: application/json" \  -d '{    "name": "Customer Support Bot",    "description": "Helpful assistant for customer inquiries",    "tone": "professional",    "language": "en",    "default_tasks": ["answer_questions", "provide_support"],    "is_active": true  }'

Sesiones

Crear sesiones de visitante anónimas para interacciones temporales.

Crear sesión

GNU Bashcreate-session.sh
curl -X POST https://app.companin.tech/api/v1/sessions/ \  -H "X-API-Key: YOUR_CLIENT_ID" \  -H "X-API-Secret: YOUR_CLIENT_SECRET" \  -H "Content-Type: application/json" \  -d '{    "assistant_id": "550e8400-e29b-41d4-a716-446655440000",    "visitor_id": "visitor-123",    "locale": "en",    "metadata": {      "source": "website",      "page": "/contact"    }  }'

Enviar mensaje en sesión

GNU Bashsend-message.sh
curl -X POST https://app.companin.tech/api/v1/sessions/${SESSION_ID}/messages \  -H "X-API-Key: YOUR_CLIENT_ID" \  -H "X-API-Secret: YOUR_CLIENT_SECRET" \  -H "Content-Type: application/json" \  -d '{    "content": "Hello, I need help with my order",    "metadata": {      "user_type": "customer"    }  }'

Conversaciones

Crear conversaciones persistentes para usuarios autenticados.

Crear conversación

GNU Bashcreate-conversation.sh
curl -X POST https://app.companin.tech/api/v1/conversations/ \  -H "X-API-Key: YOUR_CLIENT_ID" \  -H "X-API-Secret: YOUR_CLIENT_SECRET" \  -H "Content-Type: application/json" \  -d '{    "assistant_id": "550e8400-e29b-41d4-a716-446655440000",    "customer_id": "user-456",    "title": "Order Support",    "locale": "en"  }'

Enviar mensaje en conversación

GNU Bashsend-conversation-message.sh
curl -X POST https://app.companin.tech/api/v1/conversations/${CONVERSATION_ID}/messages \  -H "X-API-Key: YOUR_CLIENT_ID" \  -H "X-API-Secret: YOUR_CLIENT_SECRET" \  -H "Content-Type: application/json" \  -d '{    "content": "Can you help me track my order?",    "metadata": {      "order_id": "12345"    }  }'

Contextos de usuario

Almacenar y gestionar el contexto del usuario para interacciones personalizadas.

Crear contexto de usuario

GNU Bashcreate-context.sh
curl -X POST https://app.companin.tech/api/v1/contexts/ \  -H "X-API-Key: YOUR_CLIENT_ID" \  -H "X-API-Secret: YOUR_CLIENT_SECRET" \  -H "Content-Type: application/json" \  -d '{    "user_reference": "user-456",    "traits": {      "name": "John Doe",      "email": "john@example.com",      "subscription_tier": "premium",      "preferences": {        "language": "en",        "notifications": true      }    }  }'

Base de conocimientos

Subir y gestionar fuentes de conocimiento para sus asistentes.

Subir archivo de conocimientos

GNU Bashupload-file.sh
curl -X POST https://app.companin.tech/api/v1/knowledge/files/ \  -H "X-API-Key: YOUR_CLIENT_ID" \  -H "X-API-Secret: YOUR_CLIENT_SECRET" \  -F "title=Product Manual" \  -F "file_type=pdf" \  -F "file=@product_manual.pdf"

Agregar par de preguntas y respuestas

GNU Bashadd-qa.sh
curl -X POST https://app.companin.tech/api/v1/knowledge/qa/ \  -H "X-API-Key: YOUR_CLIENT_ID" \  -H "X-API-Secret: YOUR_CLIENT_SECRET" \  -H "Content-Type: application/json" \  -d '{    "question": "What are your business hours?",    "answer": "We are open Monday to Friday, 9 AM to 6 PM EST.",    "tags": ["hours", "support"]  }'

Casos de uso

Chatbot de Soporte al Cliente

JavaScriptsupport-chatbot.js
// 1. Obtener token de widget para chat basado en navegadorasync function getWidgetToken() {  const response = await fetch('https://app.companin.tech/api/v1/auth/widget-token', {    method: 'POST',    headers: { 'Content-Type': 'application/json' },    body: JSON.stringify({ client_id: 'YOUR_CLIENT_ID' })  });  return (await response.json()).token;}// 2. Crear una sesión para visitante anónimoasync function startSupportSession(token, assistantId) {  const response = await fetch('https://app.companin.tech/api/v1/sessions/', {    method: 'POST',    headers: {      'Authorization': `Bearer ${token}`,      'Content-Type': 'application/json'    },    body: JSON.stringify({      assistant_id: assistantId,      visitor_id: 'visitor-' + Date.now(),      metadata: { source: 'support_widget' }    })  });  return await response.json();}// 3. Enviar mensaje del cliente y obtener respuesta de IAasync function sendMessage(token, sessionId, message) {  const response = await fetch(`https://app.companin.tech/api/v1/sessions/${sessionId}/messages`, {    method: 'POST',    headers: {      'Authorization': `Bearer ${token}`,      'Content-Type': 'application/json'    },    body: JSON.stringify({      content: message,      metadata: { user_type: 'customer' }    })  });  return await response.json();}// Ejemplo de usoconst token = await getWidgetToken();const session = await startSupportSession(token, 'assistant-uuid');const result = await sendMessage(token, session.data.id, 'Necesito ayuda con mi pedido');

Asistente de Producto de Comercio Electrónico

JavaScriptecommerce-assistant.js
// 1. Crear contexto de usuario para personalizaciónasync function createUserContext(userId, userData) {  const response = await fetch('https://app.companin.tech/api/v1/contexts/', {    method: 'POST',    headers: {      'X-API-Key': 'YOUR_CLIENT_ID',      'X-API-Secret': 'YOUR_CLIENT_SECRET',      'Content-Type': 'application/json'    },    body: JSON.stringify({      user_reference: userId,      traits: {        name: userData.name,        purchase_history: userData.purchases,        preferences: userData.preferences      }    })  });  return await response.json();}// 2. Crear conversación persistente con contextoasync function startPersonalizedChat(assistantId, userId) {  const response = await fetch('https://app.companin.tech/api/v1/conversations/', {    method: 'POST',    headers: {      'X-API-Key': 'YOUR_CLIENT_ID',      'X-API-Secret': 'YOUR_CLIENT_SECRET',      'Content-Type': 'application/json'    },    body: JSON.stringify({      assistant_id: assistantId,      customer_id: userId,      user_context_id: userId,      title: 'Product Recommendations',      metadata: { source: 'product_page' }    })  });  return await response.json();}// 3. Chatear con conocimiento del productoasync function askAboutProduct(conversationId, question) {  const response = await fetch(`https://app.companin.tech/api/v1/conversations/${conversationId}/messages`, {    method: 'POST',    headers: {      'X-API-Key': 'YOUR_CLIENT_ID',      'X-API-Secret': 'YOUR_CLIENT_SECRET',      'Content-Type': 'application/json'    },    body: JSON.stringify({      content: question,      metadata: { context: 'product_inquiry' }    })  });  return await response.json();}// Ejemplo de usoawait createUserContext('user-123', {  name: 'Alice',  purchases: ['laptop-1', 'mouse-2'],  preferences: { category: 'electronics' }});const conversation = await startPersonalizedChat('assistant-uuid', 'user-123');const result = await askAboutProduct(conversation.data.id, '¿Qué laptop recomiendas?');

Sistema de Gestión del Conocimiento

JavaScriptknowledge-management.js
// 1. Subir documentación del productoasync function uploadDocumentation(file, title) {  const formData = new FormData();  formData.append('title', title);  formData.append('file_type', 'pdf');  formData.append('file', file);  const response = await fetch('https://app.companin.tech/api/v1/knowledge/files/', {    method: 'POST',    headers: {      'X-API-Key': 'YOUR_CLIENT_ID',      'X-API-Secret': 'YOUR_CLIENT_SECRET'    },    body: formData  });  return await response.json();}// 2. Agregar entradas de FAQasync function addFAQ(question, answer, tags) {  const response = await fetch('https://app.companin.tech/api/v1/knowledge/qa/', {    method: 'POST',    headers: {      'X-API-Key': 'YOUR_CLIENT_ID',      'X-API-Secret': 'YOUR_CLIENT_SECRET',      'Content-Type': 'application/json'    },    body: JSON.stringify({      question,      answer,      tags,      source: 'manual'    })  });  return await response.json();}// 3. Agregar contenido webasync function addWebContent(url, title) {  const response = await fetch('https://app.companin.tech/api/v1/knowledge/urls/', {    method: 'POST',    headers: {      'X-API-Key': 'YOUR_CLIENT_ID',      'X-API-Secret': 'YOUR_CLIENT_SECRET',      'Content-Type': 'application/json'    },    body: JSON.stringify({      url,      title    })  });  return await response.json();}// Ejemplo de usoconst fileUpload = await uploadDocumentation(pdfFile, 'User Manual v2.0');const faq = await addFAQ(  '¿Cómo restablezco mi contraseña?',  'Ve a configuración y haz clic en "Restablecer contraseña"...',  ['password', 'security']);const webContent = await addWebContent(  'https://example.tech/blog/new-features',  'Anuncio de nuevas características');

Ejemplos

Obtener Token Widget

GNU Bashrequest.sh
curl -X POST https://app.companin.tech/api/v1/auth/widget-token \  -H "Content-Type: application/json" \  -d '{"client_id":"YOUR_CLIENT_ID"}'

Crear Sesión

JavaScriptcreateSession.js
fetch('https://app.companin.tech/api/v1/sessions', {  method: 'POST',  headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },  body: JSON.stringify({ assistant_id: 'ASSISTANT_UUID' })})

Soporte CORS

  • Todos los endpoints admiten CORS para integraciones web
  • Las solicitudes preflight se manejan automáticamente
  • Las credenciales son compatibles con solicitudes autenticadas