部分内容需要魔法。如果想要解决魔法问题直接跳到
原文摘要
地址在这:platform.openai.com/docs/quicks… ,需要魔法。
build-your-application
pricing
跟着做
拉取项目
github项目clone下来。 openai/openai-quickstart-node: Node.js example app from the OpenAI API quickstart tutorial (github.com)
package.json
react18 + nextjs的项目 ,另外加入openai的sdk,node环境建议16+。
替换环境变量文件
clone下来时是.evn.example,文件名也要改为.env。
OPENAI_API_KEY是openai的secret API key,可通过下面链接添加
platform.openai.com/docs/quicks… ,需要魔法
运行项目
npm i && npm run dev
关键代码
生成提示词
pages\api\generate.js 底部,生成提示词函数,接收一种动物,生成提示词并返回。可以看到生成的提示词中有诉求 Suggest three names for an animal that is a superhero. 。 也有举例
Animal: Cat
Names: Captain Sharpclaw, Agent Fluffball, The Incredible Feline
Animal: Dog
Names: Ruff the Protector, Wonder Canine, Sir Barks-a-Lot
最后提问一个Animal让他回答Names
Animal: ${capitalizedAnimal}
Names:
function generatePrompt(animal) {
const capitalizedAnimal = animal[0].toUpperCase() + animal.slice(1).toLowerCase();
return `Suggest three names for an animal that is a superhero.
Animal: Cat
Names: Captain Sharpclaw, Agent Fluffball, The Incredible Feline
Animal: Dog
Names: Ruff the Protector, Wonder Canine, Sir Barks-a-Lot
Animal: ${capitalizedAnimal}
Names:`;
}
真正请求
参数:
model:模型
prompt:提示词
temperature:热烈程度(大概是情绪之类的)
const completion = await openai.createCompletion({
model: "text-davinci-003",
prompt: generatePrompt(req.body.animal),
temperature: 0.6,
});
收费之类
对于text-davinci-003模型,数据更新至2021年6月,单个请求不能超过4096个token或3000个单词,一个token大约是4个字符或0.75个单词。
收费也是按1000个token来收费,根据不同的模型有不同的标准。每个账号前三个月有5刀免费配额。
项目如何添加魔法
相关issue:github.com/openai/open…
使用deno代理 dash.deno.com ,直接创建playground,把代码粘贴进去save就行了。代码就是个简单的转发。
Deno.serve(async (request) => {
const url = new URL(request.url);
url.host = "api.openai.com";
console.log(url, request);
return await fetch(url, request);
});
真实请求地址
platform.openai.com/docs/models…
text-davinci-003模型需要添加/v1
然后openai sdk修改配置,访问deno的代理:
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
// 填自己的deno地址
basePath: "https://abc.deno.dev/v1"
});