Thực hiện lời gọi API đầu tiên
Bây giờ rằng mọi thứ đã được thiết lập, hãy thực hiện lời gọi API đầu tiên của chúng ta. Chúng ta sẽ bắt đầu với
một yêu cầu khởi tạo text đơn giản.
Tạo một file mới trong dự án của bạn, hãy gọi nó là openaiService.js. File này sẽ xử lí tất cả tương tác API
của chúng ta:
‘use strict’;
const { Configuration, OpenAIApi } = require(‘openai’);
const configuration = new Configuration({
apiKey: ‘YOUR_API_KEY’, // Replace with your actual API key
});const openai = new OpenAIApi(configuration);
async function generateText(prompt) {
try {
const response = await openai.createCompletion({
model: ‘text-davinci-003’,
prompt: prompt,
temperature: 0.7,
max_tokens: 256,
});
return response.data.choices[0].text;
} catch (error) {
console.error(‘Error generating text:’, error);
throw error;
}
}module.exports = { generateText };
Trong code này, chúng ta đang thiết lập máy khách Openai API và định nghĩa một hàm để khởi tạo text dựa trên một
prompt. Tham số temperature kiểm soát độ tùy biến của đầu ra, và max_tokens giới hạn độ dài của text khởi tạo.