Node.js 调用 OpenAI API - 完整指南与示例
要调用 OpenAI API,需要在 Node.js 中安装 OpenAI 官方提供的 npm 包。首先,您需要在 OpenAI 网站上注册并获取访问密钥。然后,按照以下步骤进行操作:
- 在终端中运行以下命令安装 OpenAI npm 包:
npm install openai
- 在您的 Node.js 代码中导入 OpenAI 模块:
const openai = require('openai');
- 设置 OpenAI 访问密钥:
const apiKey = 'YOUR_OPENAI_API_KEY';
openai.apiKey = apiKey;
- 调用 OpenAI API:
const prompt = 'In a shocking finding, scientists discovered a herd of unicorns living in a remote, previously unexplored valley, in the Andes Mountains. Even more surprising to the researchers was the fact that the unicorns spoke perfect English.';
const model = 'davinci';
const params = {
prompt: prompt,
model: model,
maxTokens: 5,
n: 1,
stop: '.'
};
openai.complete(params)
.then((response) => {
console.log(response.data.choices[0].text);
})
.catch((error) => {
console.error(error);
});
在这个例子中,我们使用 OpenAI 完成 API 来生成一个包含 5 个单词的句子,其中包含在一个假想的新闻报道中发现的神秘生物。我们使用 davinci 模型来完成这个任务。完成后,我们将打印生成的句子。
这是一个简单的例子,您可以按照文档中提供的参数和模型选择等选项来使用 OpenAI API。
原文地址: https://www.cveoy.top/t/topic/m84e 著作权归作者所有。请勿转载和采集!