Sending Messages and Getting AI Responses
This guide explains how to send user messages and receive AI responses using the ZeroinAI Chat Service API.
Overview
Once you've created a chat session, you can send user messages to the API and receive AI-generated responses. The API handles the conversation context automatically, ensuring that the AI responses are relevant to the ongoing conversation.
Prerequisites
- You have created a chat session and have a valid
chat_id - You have your ZeroinAI API Key
Step-by-Step Guide
1. Prepare Your Request
To send a message, you'll need to make a POST request to the /chats/messages/ endpoint with your API key and a JSON body containing the chat_id and message content.
// Example in JavaScript
const sendMessage = async (chatId, messageContent) => {
const response = await fetch('https://api.zeroinai.com/micro-apps/for-api-providers/chat-service/chats/messages/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'YOUR_API_KEY'
},
body: JSON.stringify({
chat_id: chatId,
content: messageContent
})
});
const data = await response.json();
return data;
};
2. Handle the AI Response
The API will respond with a JSON object containing the AI's response message. This is what you'll display to the user.
// Example response handling
const chatId = localStorage.getItem('currentChatId');
const userMessage = "How can I reset my password?";
sendMessage(chatId, userMessage)
.then(aiResponse => {
console.log('AI Response:', aiResponse.content);
// Display the AI response to the user
displayMessage(aiResponse.content, false); // false indicates it's not a user message
})
.catch(error => {
console.error('Error sending message:', error);
});
3. Update Your UI
After receiving the AI response, update your user interface to display both the user's message and the AI's response. Here's a simple example:
function displayMessage(content, isUser) {
const chatContainer = document.getElementById('chat-container');
const messageElement = document.createElement('div');
messageElement.className = isUser ? 'user-message' : 'ai-message';
messageElement.textContent = content;
chatContainer.appendChild(messageElement);
// Scroll to the bottom to show the latest message
chatContainer.scrollTop = chatContainer.scrollHeight;
}
Token Usage
Each message exchange consumes tokens from your chat session's token_limit. The exact number of tokens used depends on:
- The length of the user's message
- The complexity of the AI's response
- The context from previous messages
If a chat session runs out of tokens, you'll receive a 402 Payment Required error. In this case, you can add more tokens using the Update Chat Tokens endpoint.
Error Handling
When sending messages, be prepared to handle these common errors:
400 Bad Request: Missingchat_idor malformed request401 Unauthorized: Invalid or missing API Key402 Payment Required: Not enough tokens remaining404 Not Found:chat_idnot found422 Unprocessable Entity: Missing or invalidcontent
async function sendMessageWithErrorHandling(chatId, content) {
try {
const response = await fetch(`${API_URL}/chats/messages/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': API_KEY
},
body: JSON.stringify({
chat_id: chatId,
content: content
})
});
if (response.status === 402) {
// Handle token limit exceeded
await addMoreTokens(chatId);
// Retry the message after adding tokens
return sendMessageWithErrorHandling(chatId, content);
}
if (!response.ok) {
throw new Error(`Error: ${response.status} ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error('Failed to send message:', error);
throw error;
}
}
Next Steps
After sending messages and receiving responses, you might want to:
- Retrieve the chat history to display the full conversation
- Add more tokens if the conversation is approaching the token limit
- Delete the chat when the conversation is complete
Complete Code Example
// Complete example of sending a message and handling the response
const API_URL = 'https://api.zeroinai.com/micro-apps/for-api-providers/chat-service';
const API_KEY = 'YOUR_API_KEY';
async function sendMessage(chatId, content) {
try {
// Show loading indicator
const loadingIndicator = document.getElementById('loading-indicator');
loadingIndicator.style.display = 'block';
// Display user message immediately
displayMessage(content, true);
const response = await fetch(`${API_URL}/chats/messages/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': API_KEY
},
body: JSON.stringify({
chat_id: chatId,
content: content
})
});
// Hide loading indicator
loadingIndicator.style.display = 'none';
if (response.status === 402) {
// Token limit exceeded
const addTokensResult = await addMoreTokens(chatId, 500);
if (addTokensResult.success) {
return sendMessage(chatId, content); // Retry with more tokens
} else {
throw new Error('Failed to add more tokens');
}
}
if (!response.ok) {
throw new Error(`Error: ${response.status} ${response.statusText}`);
}
const aiResponse = await response.json();
// Display AI response
displayMessage(aiResponse.content, false);
return aiResponse;
} catch (error) {
// Hide loading indicator
document.getElementById('loading-indicator').style.display = 'none';
// Display error message
displayErrorMessage('Failed to get response from AI assistant');
console.error('Failed to send message:', error);
throw error;
}
}
function displayMessage(content, isUser) {
const chatContainer = document.getElementById('chat-container');
const messageElement = document.createElement('div');
messageElement.className = isUser ? 'user-message' : 'ai-message';
messageElement.textContent = content;
chatContainer.appendChild(messageElement);
chatContainer.scrollTop = chatContainer.scrollHeight;
}
function displayErrorMessage(message) {
const chatContainer = document.getElementById('chat-container');
const errorElement = document.createElement('div');
errorElement.className = 'error-message';
errorElement.textContent = message;
chatContainer.appendChild(errorElement);
chatContainer.scrollTop = chatContainer.scrollHeight;
}
// Example usage
const chatId = sessionStorage.getItem('chatId');
const messageInput = document.getElementById('message-input');
const sendButton = document.getElementById('send-button');
sendButton.addEventListener('click', () => {
const content = messageInput.value.trim();
if (content) {
sendMessage(chatId, content);
messageInput.value = ''; // Clear input after sending
}
});