0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

OpenAiのAPIを設定する @yukilulu0229

Posted at

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();

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?