使用 Node.js 和代理调用 OpenAI GPT-3 API 完成文本生成
以下是一个示例代码,使用 Node.js 调用 OpenAI GPT-3 API 完成文本生成,并使用代理:
const axios = require('axios');
const openai = require('openai');
const HttpsProxyAgent = require('https-proxy-agent');
// 设置代理地址
const proxy = 'http://your-proxy-address:port';
// 创建代理对象
const agent = new HttpsProxyAgent(proxy);
// 设置 OpenAI API key
openai.api_key = 'your-api-key';
// 设置 OpenAI 请求参数
const prompt = 'Once upon a time,';
const model = 'text-davinci-002';
const maxTokens = 50;
// 发送 OpenAI 请求
axios.post('https://api.openai.com/v1/completions', {
prompt: prompt,
model: model,
max_tokens: maxTokens
}, {
httpsAgent: agent, // 设置代理
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${openai.api_key}`
}
}).then(response => {
console.log(response.data.choices[0].text);
}).catch(error => {
console.log(error);
});
需要注意的是,上述代码需要安装以下依赖包:
- axios:用于发送 HTTP 请求
- openai:OpenAI 官方提供的 Node.js SDK
- https-proxy-agent:用于创建代理对象
可以通过以下命令安装这些依赖包:
npm install axios openai https-proxy-agent
原文地址: https://www.cveoy.top/t/topic/lJ3w 著作权归作者所有。请勿转载和采集!