動機
これだとpages/api/generate.jsをNextのGUIから叩いているが面倒だったので
単一のhoge.jsファイルを作ってnode hoge.js
打ったら走るように切り出した
GitHub - openai/openai-quickstart-node: Node.js example app from the OpenAI API quickstart tutorial
手順
キー取得
api-keysのページからキーを取得
準備
export OPENAI_API_KEY=[さっき取得したキー]
npm install openai
hoge.jsを作成して次のように書く, 偉大なるフェミニスト様に対してChatGPTはどのようなcompletionを見せてくれるか!?
import { Configuration, OpenAIApi } from "openai";
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
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:`;
}
async function main(animal) {
if (!configuration.apiKey) {
console.error(
"OpenAI API key not configured, please follow instructions in README.md"
);
return;
}
if (animal.trim().length === 0) {
console.error("Please enter a valid animal");
return;
}
try {
const completion = await openai.createCompletion({
model: "text-davinci-003",
prompt: generatePrompt(animal),
temperature: 0.6,
});
console.log(completion.data.choices[0].text);
} catch (error) {
if (error.response) {
console.error(error.response.status, error.response.data);
} else {
console.error(`Error with OpenAI API request: ${error.message}`);
}
}
}
main("フェミニスト");
実行
❯ node hoge.js
Femme Force, Mighty Maiden, Super She-ro
感想
僕もプロ驚き屋になってプロトタイプを製品として紹介したりカスみたいな有料ノート売りてえええ!!
あ、ろいじぇね