Skip to main content

Backend Integration

This guide explains how to integrate with the Binj Chat Service API from your backend.

Overview

The Binj Chat Service provides a RESTful API that allows you to create and manage chat sessions programmatically. This is useful for server-side integration or when you need more control over the chat flow.

Prerequisites

  • You have your Binj API Key
  • You have access to the Binj Chat Service API

Getting a Chat ID

A chat ID is required for all interactions with the chat service. There are two ways to get a chat ID:

1. Creating a New Chat Session

To create a new chat session and get a chat ID, make a POST request to the /chats/ endpoint.

Input Parameters

ParameterTypeRequiredDescription
token_limitnumberYesToken limits put limits on chat conversations. The higher the limit, the more a user can interact with it. A token limit of 2000 is equal to 25000 words, typically involving 125 long conversation turns (200 words per message) or 500 medium conversation turns (50-70 words per message).

Example Request

// Example in JavaScript (Node.js)
const axios = require('axios');

async function createChatSession() {
try {
const response = await axios.post(
'https://api.zeroinai.com/micro-apps/for-api-providers/chat-service/chats/',
{
token_limit: 1000.0 // Set your desired token limit
},
{
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'YOUR_API_KEY'
}
}
);

const chatId = response.data.chat_id;
console.log('Chat created with ID:', chatId);
return chatId;
} catch (error) {
console.error('Error creating chat session:', error.response?.data || error.message);
throw error;
}
}

Response Format

A successful response will return a JSON object with the following structure:

{
"chat_id": "18c0bf36-7ae7-4dd6-96ea-be2366475685",
"created_at": "2023-05-12T10:15:30Z",
"agent_name": "Binj Assistant",
"creator_company_name": "Binj",
"token_limit": 1000.0,
"token_used": 0.0,
"deleted": false,
"messages": []
}

2. Retrieving an Existing Chat Configuration

If you've already created a chat configuration in the admin portal, you can retrieve its details using the config ID:

// Example in JavaScript (Node.js)
const axios = require('axios');

async function getChatConfig(configId) {
try {
const response = await axios.get(
`https://api.zeroinai.com/micro-apps/for-api-providers/chat-service/admin/chat-config/${configId}`,
{
headers: {
'X-API-Key': 'YOUR_API_KEY'
}
}
);

console.log('Chat configuration retrieved:', response.data);
return response.data;
} catch (error) {
console.error('Error retrieving chat configuration:', error.response?.data || error.message);
throw error;
}
}

// Example usage
const configId = '18c0bf36-7ae7-4dd6-96ea-be2366475685';
getChatConfig(configId);

Response Format

A successful response will return a JSON object with the chat configuration details:

{
"config_id": "18c0bf36-7ae7-4dd6-96ea-be2366475685",
"agent_name": "Binj Assistant",
"company_name": "Binj",
"primary_color": "#4CAF50",
"header_text": "Chat with our AI",
"logo_url": "https://example.com/logo.png",
"welcome_message": "Hello! How can I help you today?",
"chat_description": "Ask me anything about our products and services.",
"full_width": false,
"start_page_title": "Welcome",
"start_page_slogan": "Get instant help from our AI assistant",
"created_at": "2023-05-10T08:30:15Z",
"updated_at": "2023-05-11T14:45:22Z"
}

Security Considerations

When integrating with the Binj Chat Service API, keep these security best practices in mind:

  1. API Key Protection: Never expose your API key in client-side code. Always make API calls from your server.

  2. API Key Security: Keep your API key secure and rotate it periodically for enhanced security.

  3. User Authentication: If you're creating chat sessions for authenticated users, associate the chat ID with the user's session to prevent unauthorized access.

  4. Rate Limiting: Implement rate limiting on your server to prevent abuse of the API.

Complete Backend Integration Example

Here's a complete example of a Node.js Express server that integrates with the Binj Chat Service API:

const express = require('express');
const axios = require('axios');
const cors = require('cors');
const app = express();
const port = 3000;

// Middleware
app.use(express.json());
app.use(cors({ origin: 'https://your-frontend-domain.com' }));

// Configuration
const API_URL = 'https://api.zeroinai.com/micro-apps/for-api-providers/chat-service';
const API_KEY = 'YOUR_API_KEY';

// Create a new chat session
app.post('/api/chats', async (req, res) => {
try {
const response = await axios.post(
`${API_URL}/chats/`,
{
token_limit: req.body.token_limit || 1000.0
},
{
headers: {
'Content-Type': 'application/json',
'X-API-Key': API_KEY
}
}
);

res.json(response.data);
} catch (error) {
console.error('Error creating chat:', error.response?.data || error.message);
res.status(error.response?.status || 500).json({
error: 'Failed to create chat session',
details: error.response?.data || error.message
});
}
});

// Send a message and get AI response
app.post('/api/messages', async (req, res) => {
try {
const { chat_id, content } = req.body;

if (!chat_id || !content) {
return res.status(400).json({ error: 'chat_id and content are required' });
}

const response = await axios.post(
`${API_URL}/chats/messages/`,
{
chat_id,
content,
role: 'user'
},
{
headers: {
'Content-Type': 'application/json',
'X-API-Key': API_KEY
}
}
);

res.json(response.data);
} catch (error) {
console.error('Error sending message:', error.response?.data || error.message);
res.status(error.response?.status || 500).json({
error: 'Failed to send message',
details: error.response?.data || error.message
});
}
});

// Get chat configuration
app.get('/api/chat-config/:configId', async (req, res) => {
try {
const { configId } = req.params;

const response = await axios.get(
`${API_URL}/admin/chat-config/${configId}`,
{
headers: {
'X-API-Key': API_KEY
}
}
);

res.json(response.data);
} catch (error) {
console.error('Error getting chat config:', error.response?.data || error.message);
res.status(error.response?.status || 500).json({
error: 'Failed to get chat configuration',
details: error.response?.data || error.message
});
}
});

// Start the server
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});

Managing Chat Tokens

Chat tokens control the amount of conversation that can happen within a chat session. You may need to increase the token limit for a chat session if users need to have longer conversations.

Increasing Chat Token Limit

To increase a chat token limit, send a PUT request to the tokens endpoint with the number of additional tokens:

curl -X 'PUT' \
'https://dev.api.zeroinai.com/micro-apps/for-api-providers/chat-service/chats/{chat_id}/tokens/' \
-H 'accept: application/json' \
-H 'x-api-key: api_key' \
-H 'Content-Type: application/json' \
-d '{
"additional_tokens": 1000
}'

This will increase the current token limit by 1000 tokens.

Accessing Chat History

You can retrieve the message history for a specific chat by its chat_id. This is useful for analytics, auditing, or resuming conversations.

curl -X 'GET' \
'https://dev.api.zeroinai.com/micro-apps/for-api-providers/chat-service/chats/{chat_id}/messages/?limit=5&offset=0' \
-H 'accept: application/json' \
-H 'x-api-key: {api_key}'

The query parameters allow you to paginate through the results:

  • limit: Maximum number of messages to return (in this example, 5)
  • offset: Number of messages to skip (for pagination)

Troubleshooting

If you encounter issues with the API integration, check the following:

  1. API Key: Ensure your API key is valid and has the necessary permissions.
  2. API Endpoints: Make sure you're using the correct API endpoints in your requests.
  3. Rate Limits: Check if you've hit any rate limits on the API.
  4. Network Issues: Verify that your server can reach the API endpoints.

For further assistance, contact support at [email protected].