Skip to main content

Retrieving Chat History

This guide explains how to retrieve the message history for a chat session using the ZeroinAI Chat Service API.

Overview​

Retrieving the chat history allows you to display the full conversation between the user and the AI assistant. This is particularly useful when a user returns to a conversation after some time or when you need to implement features like conversation export or analysis.

Prerequisites​

  • You have a valid chat_id from a previously created chat session
  • You have your ZeroinAI API Key

Step-by-Step Guide​

1. Prepare Your Request​

To retrieve the chat history, you'll need to make a GET request to the /chats/{chat_id}/messages/ endpoint with your API key. You can also use pagination parameters to control the number of messages returned.

// Example in JavaScript
const getChatHistory = async (chatId, limit = 10, offset = 0) => {
const response = await fetch(`https://api.zeroinai.com/micro-apps/for-api-providers/chat-service/chats/${chatId}/messages/?limit=${limit}&offset=${offset}`, {
method: 'GET',
headers: {
'X-API-Key': 'YOUR_API_KEY'
}
});

const data = await response.json();
return data;
};

2. Handle the Response​

The API will respond with a paginated list of messages, sorted by timestamp in ascending order (oldest first).

// Example response handling
const chatId = localStorage.getItem('currentChatId');

getChatHistory(chatId)
.then(history => {
console.log('Total messages:', history.total);

// Display each message in the UI
history.items.forEach(message => {
displayMessage(message.content, message.is_user);
});

// Check if there are more messages to load
if (history.total > history.limit) {
showLoadMoreButton();
}
})
.catch(error => {
console.error('Error retrieving chat history:', error);
});

3. Implement Pagination​

If there are many messages in the chat history, you'll want to implement pagination to load them in batches.

let currentOffset = 0;
const messagesPerPage = 10;

function loadMoreMessages() {
currentOffset += messagesPerPage;

getChatHistory(chatId, messagesPerPage, currentOffset)
.then(history => {
// Display the additional messages
history.items.forEach(message => {
displayMessage(message.content, message.is_user);
});

// Hide the "Load More" button if we've loaded all messages
if (currentOffset + messagesPerPage >= history.total) {
hideLoadMoreButton();
}
})
.catch(error => {
console.error('Error loading more messages:', error);
});
}

Displaying Messages in Chronological Order​

The API returns messages sorted by timestamp in ascending order (oldest first), which is typically how you want to display them in a chat interface. If you need to display them in reverse order (newest first), you can reverse the array:

// Display messages in reverse chronological order (newest first)
getChatHistory(chatId)
.then(history => {
const reversedMessages = [...history.items].reverse();

reversedMessages.forEach(message => {
displayMessage(message.content, message.is_user);
});
});

Error Handling​

When retrieving chat history, be prepared to handle these common errors:

  • 401 Unauthorized: Invalid or missing API Key
  • 404 Not Found: chat_id not found
async function getChatHistoryWithErrorHandling(chatId, limit = 10, offset = 0) {
try {
const response = await fetch(`${API_URL}/chats/${chatId}/messages/?limit=${limit}&offset=${offset}`, {
method: 'GET',
headers: {
'X-API-Key': API_KEY
}
});

if (!response.ok) {
if (response.status === 404) {
// Chat not found - might have been deleted or expired
throw new Error('Chat session not found. It may have been deleted or expired.');
} else {
throw new Error(`Error: ${response.status} ${response.statusText}`);
}
}

return await response.json();
} catch (error) {
console.error('Failed to retrieve chat history:', error);
throw error;
}
}

Next Steps​

After retrieving the chat history, you might want to:

  1. Send a new message to continue the conversation
  2. Delete the chat if the conversation is complete
  3. Implement features like exporting the conversation or analyzing the content

Complete Code Example​

// Complete example of retrieving and displaying chat history
const API_URL = 'https://api.zeroinai.com/micro-apps/for-api-providers/chat-service';
const API_KEY = 'YOUR_API_KEY';

async function loadChatHistory(chatId) {
try {
// Show loading indicator
const loadingIndicator = document.getElementById('history-loading-indicator');
loadingIndicator.style.display = 'block';

// Clear existing messages
const chatContainer = document.getElementById('chat-container');
chatContainer.innerHTML = '';

let allMessages = [];
let hasMoreMessages = true;
let offset = 0;
const limit = 20;

// Load all messages using pagination
while (hasMoreMessages) {
const response = await fetch(`${API_URL}/chats/${chatId}/messages/?limit=${limit}&offset=${offset}`, {
method: 'GET',
headers: {
'X-API-Key': API_KEY
}
});

if (!response.ok) {
throw new Error(`Error: ${response.status} ${response.statusText}`);
}

const history = await response.json();
allMessages = [...allMessages, ...history.items];

offset += limit;
hasMoreMessages = offset < history.total;
}

// Hide loading indicator
loadingIndicator.style.display = 'none';

// Display all messages
allMessages.forEach(message => {
displayMessage(message.content, message.is_user);
});

return allMessages;
} catch (error) {
// Hide loading indicator
document.getElementById('history-loading-indicator').style.display = 'none';

// Display error message
displayErrorMessage('Failed to load chat history');

console.error('Failed to load chat history:', 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);
}

function displayErrorMessage(message) {
const chatContainer = document.getElementById('chat-container');
const errorElement = document.createElement('div');

errorElement.className = 'error-message';
errorElement.textContent = message;

chatContainer.appendChild(errorElement);
}

// Example usage
const chatId = sessionStorage.getItem('chatId');
document.addEventListener('DOMContentLoaded', () => {
if (chatId) {
loadChatHistory(chatId);
} else {
displayErrorMessage('No active chat session found');
}
});