要在Node.js中使用OpenAI,您可以使用OpenAI官方提供的API。首先,您需要注册并获得一个OpenAI API密钥。然后,您可以使用HTTP请求库(如Axios或node-fetch)向OpenAI API发送请求。
以下是一个简单的示例代码:
const axios = require('axios');
// 替换为您的OpenAI API密钥
const apiKey = 'YOUR_API_KEY';
// 发送请求给OpenAI GPT-3模型
async function callOpenAI() {
const prompt = "你好,我是零声教学助手。";
const maxTokens = 50;
try {
const response = await axios.post(
'https://api.openai.com/v1/engines/davinci-codex/completions',
{
prompt: prompt,
max_tokens: maxTokens
},
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
}
}
);
console.log(response.data.choices[0].text);
} catch (error) {
console.error(error);
}
}
callOpenAI();
请确保替换YOUR_API_KEY
为您自己的实际API密钥。这个示例使用了GPT-3模型(davinci-codex引擎),但您也可以根据需要选择其他模型和引擎。
请注意,在使用OpenAI API时,请遵守他们的使用政策和指导方针,并确保合法和合理地使用该服务。
内容由零声教学AI助手提供,问题来源于学员提问