git clone https://github.com/openai/openai-quickstart-node.git
const completion = await openai.createCompletion({
model: "text-davinci-003",
prompt: generatePrompt(req.body.animal),
temperature: 0.6,
});
text-davinci-003是使用的模型,他是专门用来处理语言相关的模型:
有兴趣可以看官网文档的解释
Text Completion(https://openai.xiniushu.com/docs/guides/completion)
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:`;
}
function generatePrompt(text) {
return `Please translate the following text into chinese:
Text: ${text}
Result:`;
}
chrome.runtime.sendMessage({ text }, function (response: any) {});
chrome.runtime.onMessage.addListener(function (
request,
sender,
sendResponse
) {
chrome.storage.sync.get(["text", "enable"], async function (result) {
const response = await fetch(API, {
method: "POST",
headers: {
"Content-Type": "application/json",
withCredentials: true,
},
body: JSON.stringify({ animal: request.text }),
});
});
});
这里要注意的是,我使用的是Vercel的Serverless部署的api,由于只是Hobby账号,所以请求有个10s限制,划的词太长的话,ChatGPT处理时间会超过10s,导致api报错。
好了,收工!