Referência completa da API para integração com a plataforma do Agente de Suporte ao Cliente. Inclui autenticação, endpoints, esquemas de solicitação/resposta e exemplos de código práticos.
A API suporta dois métodos de autenticação:
Gere tokens JWT de curta duração para autenticação de widgets. Este endpoint permite que widgets obtenham tokens seguros usando apenas o client_id, evitando a necessidade de expor o client_secret em ambientes de navegador.
Se você instalar o widget com a tag de script padrão, não precisa chamar isso você mesmo — o embed realiza a troca ao carregar. Chame-o diretamente apenas quando estiver construindo sua própria superfície de chat contra a API. A Origem da solicitação deve estar na lista de origens permitidas do aplicativo, e os mints são limitados a 30 por minuto por IP.
curl -X POST https://app.companin.tech/api/v1/auth/widget-token \ -H "Content-Type: application/json" \ -H "Origin: https://your-site.example" \ -d '{ "client_id": "YOUR_CLIENT_ID" }'Resposta:
{ "token": "eyJ...", "expires_in": 3600, "token_type": "Bearer" }As solicitações da API têm um limite de taxa de 100 por hora por organização. Exceder o limite retorna HTTP 429; respostas que incluem uma dica de espera contêm um cabeçalho Retry-After. O tráfego do widget é medido separadamente e não é contabilizado contra este orçamento. Se você precisar de um limite maior, entre em contato conosco.
Todos os erros da API retornam respostas JSON estruturadas com códigos de status, detalhes do erro e campos de dados opcionais.
{ "status": "error", "status_code": 401, "detail": "Authentication required - ...", "data": null }Chame esses endpoints do seu servidor. O X-API-Secret nunca deve chegar ao navegador, e solicitações do navegador do seu próprio domínio são rejeitadas pelo CORS — veja Suporte CORS abaixo.
Gerencie as personas do agente de IA com configurações personalizadas.
curl -X GET https://app.companin.tech/api/v1/agents/ \ -H "X-API-Key: YOUR_CLIENT_ID" \ -H "X-API-Secret: YOUR_CLIENT_SECRET"curl -X POST https://app.companin.tech/api/v1/agents/ \ -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 agent for customer inquiries", "tone": "professional", "language": "en", "default_tasks": ["answer_questions", "provide_support"], "is_active": true }'Crie sessões de visitantes anônimos para interações temporárias.
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 '{ "agent_id": "550e8400-e29b-41d4-a716-446655440000", "visitor_id": "visitor-123", "locale": "en", "metadata": { "source": "website", "page": "/contact" } }'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" } }'Crie conversas persistentes para usuários autenticados.
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 '{ "agent_id": "550e8400-e29b-41d4-a716-446655440000", "customer_id": "user-456", "title": "Order Support", "locale": "en" }'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" } }'Armazene e gerencie o contexto do usuário para interações personalizadas.
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 } } }'Faça upload e gerencie fontes de conhecimento para seus agentes.
Nota: POST /api/v1/knowledge/files/ registra uma entrada de arquivo de conhecimento e seus metadados — não aceita o conteúdo do arquivo. Para fazer o upload do próprio arquivo, use o painel, ou POST dados de formulário multipart para /knowledge-base/ com uma sessão de painel autenticada.
# Registers a knowledge file entry (metadata only — see the note above). 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" \ -H "Content-Type: application/json" \ -d '{ "title": "Product Manual", "file_type": "pdf", "summary": "Installation and troubleshooting guide" }'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"] }'// 1. Obter token do widget para chat baseado em navegador async 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. Criar uma sessão para visitante anônimo async function startSupportSession(token, agentId) { const response = await fetch('https://app.companin.tech/api/v1/sessions/', { method: 'POST', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ agent_id: agentId, visitor_id: 'visitor-' + Date.now(), metadata: { source: 'support_widget' } }) }); return await response.json(); } // 3. Enviar mensagem do cliente e obter resposta da IA async 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(); } // Exemplo de uso const token = await getWidgetToken(); const session = await startSupportSession(token, 'agent-uuid'); const result = await sendMessage(token, session.data.id, 'Preciso de ajuda com meu pedido');// 1. Criar contexto de usuário para personalização async 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. Criar conversa persistente com contexto async function startPersonalizedChat(agentId, 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({ agent_id: agentId, customer_id: userId, user_context_id: userId, title: 'Product Recommendations', metadata: { source: 'product_page' } }) }); return await response.json(); } // 3. Conversar com conhecimento do produto async 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(); } // Exemplo de uso await createUserContext('user-123', { name: 'Alice', purchases: ['laptop-1', 'mouse-2'], preferences: { category: 'electronics' } }); const conversation = await startPersonalizedChat('agent-uuid', 'user-123'); const result = await askAboutProduct(conversation.data.id, 'Qual laptop você recomenda?');// 1. Faça upload da documentação do produto async function registerDocumentation(title, summary) { // Registers the entry + its metadata. File content is uploaded separately // (dashboard, or multipart POST to /knowledge-base/ with a dashboard session). 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', 'Content-Type': 'application/json' }, body: JSON.stringify({ title, file_type: 'pdf', summary }) }); return await response.json(); } // 2. Adicione entradas de FAQ async 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. Adicione conteúdo da web async 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(); } // Exemplo de uso const fileEntry = await registerDocumentation('User Manual v2.0', 'Setup and troubleshooting'); const faq = await addFAQ( 'Como redefino minha senha?', 'Vá para as configurações e clique em "Redefinir Senha"...', ['password', 'security'] ); const webContent = await addWebContent( 'https://example.tech/blog/new-features', 'Anúncio de Novos Recursos' );curl -X POST https://app.companin.tech/api/v1/auth/widget-token \ -H "Content-Type: application/json" \ -d '{"client_id":"YOUR_CLIENT_ID"}'fetch('https://app.companin.tech/api/v1/sessions', { method: 'POST', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ agent_id: 'AGENT_UUID' }) })