アプリケーション開発ポータルサイト
ServerNote.NET
Amazon.co.jpでPC関連商品タイムセール開催中!
カテゴリー【OpenAI/ChatGPTNode.jsJavaScript
【OpenAI Node.js API】Chat/Create chat completionのサンプル
POSTED BY
2023-06-06

OpenAI公式のAPIに、モデル「gpt-3.5-turbo」を使用した「Chat」のサンプルが正式追加された。

https://platform.openai.com/docs/api-reference/chat/create?lang=node.js

上記公式を参考に、過去のやりとりを含めて連続して会話を行うサンプルが以下です。

JavaScriptopenai_api_create_chat_completion.jsGitHub Source
const { Configuration, OpenAIApi } = require("openai");

const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

(async () => {
  const completion = await openai.createChatCompletion({
    model: "gpt-3.5-turbo",
    messages: [
        { role: "user", content: "When will the GPT-4 API be available?" }
    ],
  });
  console.log(completion.data.choices[0].message);

  const completion2 = await openai.createChatCompletion({
    model: "gpt-3.5-turbo",
    messages: [
        { role: "user", content: "When will the GPT-4 API be available?" },
        completion.data.choices[0].message,
        { role: "user", content: "日本語でお願いします。" }
    ],
  });
  console.log(completion2.data.choices[0].message);

})();

実行結果

node openai_api_create_chat_completion.js
{
  role: 'assistant',
  content: 'As an AI language model, I am not privy to the specific release dates of new software or APIs. However, it is worth noting that the development of artificial intelligence technology is a complex process and the release of new products or updates may be subject to change or delay.'
}
{
  role: 'assistant',
  content: '申し訳ありません。GPT-4 APIのリリース日については確かな情報はありません。人工知能技術の開発は複雑なプロセスであり、新しい製品やアップデートのリリースには 変更や遅延がある場合があります。'
}

最初は英語で質問して、Assistantからの返答をそのまま次の呼び出しのmessages引数に設定(completion.data.choices[0].message)するところがポイントです。
今回の例では、英語での質問なので英語で返してくるでしょうから、「日本語でお願い」とだけ言えば、前の会話を参考にして同じ答えを日本語で返してくれます。

なお、

TypeError: openai.createChatCompletion is not a function

と言われてしまった場合、openaiのモジュールが古い(createChatCompletion関数が無い)可能性大。以下再インストールする。

npm install openai

changed 1 package, and audited 687 packages in 5s
※本記事は当サイト管理人の個人的な備忘録です。本記事の参照又は付随ソースコード利用後にいかなる損害が発生しても当サイト及び管理人は一切責任を負いません。
※本記事内容の無断転載を禁じます。
【WEBMASTER/管理人】
自営業プログラマーです。お仕事ください!
ご連絡は以下アドレスまでお願いします★

☆ServerNote.NETショッピング↓
ShoppingNote / Amazon.co.jp
☆お仲間ブログ↓
一人社長の不動産業務日誌
【キーワード検索】