import axios from 'axios';
async function streamingChat() {
try {
const response = await axios.post('https://router.requesty.ai/v1/chat/completions', {
model: "openai/gpt-4o",
messages: [
{ role: "user", content: "Write a short story about AI" }
],
stream: true
}, {
headers: {
'Authorization': `Bearer ${process.env.REQUESTY_API_KEY}`,
'Content-Type': 'application/json'
},
responseType: 'stream'
});
response.data.on('data', (chunk) => {
const lines = chunk.toString().split('\n');
for (const line of lines) {
const trimmedLine = line.trim();
if (!trimmedLine || !trimmedLine.startsWith('data:')) continue;
const data = trimmedLine.substring(5).trim();
if (data === '[DONE]') {
console.log('\nStream completed');
return;
}
try {
const parsed = JSON.parse(data);
const content = parsed.choices?.[0]?.delta?.content;
if (content) {
process.stdout.write(content);
}
} catch (e) {
// Skip invalid JSON lines
}
}
});
} catch (error) {
console.error('Error:', error.response?.data || error.message);
}
}
streamingChat();