Template for messaging a bot with streaming using the provided API calls.
The following code can be used to output the response of the Chatzuri API in a stream format, giving the appearance of natural, hand typed text.
Replace <Your-Secret-Key> and <Your Agent ID> before implementation.
// streamer.js
const axios = require('axios');
const { Readable } = require('stream');
const apiKey = '<Your-Secret-Key>';
const chatId = '<Your Agent ID>';
const apiUrl = 'https://www.chatzuri.com/api/v1/chat';
const messages = [
{ content: '<Your query here>', role: 'user' }
];
const authorizationHeader = `Bearer ${apiKey}`;
async function readChatbotReply() {
try {
const response = await axios.post(apiUrl, {
messages,
chatId,
stream: true,
temperature: 0
}, {
headers: {
Authorization: authorizationHeader,
'Content-Type': 'application/json'
},
responseType: 'stream'
});
const readable = new Readable({
read() {}
});
response.data.on('data', (chunk) => {
readable.push(chunk);
});
response.data.on('end', () => {
readable.push(null);
});
const decoder = new TextDecoder();
let done = false;
readable.on('data', (chunk) => {
const chunkValue = decoder.decode(chunk);
process.stdout.write(chunkValue);
});
readable.on('end', () => {
done = true;
});
} catch (error) {
console.log('Error:', error.message);
}
}
readChatbotReply();How to handle API errors gracefully
If there are any errors during the API request, appropriate HTTP status codes will be returned along with error messages in the response body.
That's it! You should now be able to create a agent using the create API.