JavaScript/Node.js Examples
// Install dependency: npm install openai
const OpenAI = require('openai');
const openai = new OpenAI({
apiKey: 'your-api-key',
baseURL: 'https://gateway.iotex.ai/v1'
});
// Simple conversation
async function simpleChat(prompt) {
try {
const completion = await openai.chat.completions.create({
messages: [{ role: 'user', content: prompt }],
model: 'gpt-3.5-turbo',
max_tokens: 1000
});
return completion.choices[0].message.content;
} catch (error) {
console.error('API call failed:', error);
throw error;
}
}
// Streaming output
async function streamChat(prompt) {
const stream = await openai.chat.completions.create({
model: 'gpt-3.5-turbo',
messages: [{ role: 'user', content: prompt }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || '');
}
}
// Usage examples
(async () => {
// Simple call
const result = await simpleChat('Write a quicksort algorithm in JavaScript');
console.log(result);
// Streaming output
console.log('\nStreaming example:');
await streamChat('Explain React Hooks usage');
})();Browser Usage with Fetch API
Last updated