Api keys を開く
create new secret key を作る
.env ファイルを作る
.env
NEXT_PUBLIC_OPENAI_KEY="XXXXXXXXXXXXXXX"
gitignoreする
.gitignore
.env
使い方
npm install
npm install openai@^4.0.0
コード
app.tsx
"use client";
import OpenAI from "openai";
const Chat = () => {
const openai = new OpenAI({
apiKey: process.env.NEXT_PUBLIC_OPENAI_KEY,
dangerouslyAllowBrowser: true,
});
const sendMessage = async () => {
//OpenAIからの返信
const gpt3Response = await openai.chat.completions.create({
messages: [{ role: "user", content: inputMessage }],
model: "gpt-3.5-turbo",
});
const botResponse = gpt3Response.choices[0].message.content;
};
};
export default Chat;
import OpenAI from "openai";
インポートする
const gpt3Response = await openai.chat.completions.create({
messages: [{ role: "user", content: inputMessage }],
model: "gpt-3.5-turbo",
});
送る側の設定
- roleでユーザーを指定する
- contentに送りたいメッセージ
- modelに使いたいモデル
const botResponse = gpt3Response.choices[0].message.content;
ボット側からの返信を格納
公式での表記
app.tsx
import OpenAI from "openai";
const openai = new OpenAI();
async function main() {
const stream = await openai.chat.completions.create({
model: "gpt-4",
messages: [{ role: "user", content: "Say this is a test" }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || "");
}
}
main();